In my web application i use hibernate and spring. Entity classes that are returned from Hibernate layer need to access other service classes in some scenarios. Entity classes are not just DTO's they contains some business logic, and to perform some business logic (like may be send out emails etc when some conditions are met) these need to access service classes. Service classes are spring beans. so what's the recommended method in such scenarios to get hold of spring beans from within these entity classes which are created outside spring context?
getUserService() method simply returns the fetched Spring bean instance of UserService class with this static method. Note that you can call any Spring managed bean here by simply passing the getBean(...) method the class for said bean. E.g.
In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.
The ListableBeanFactory interface provides getBeanDefinitionNames() method which returns the names of all the beans defined in this factory. This interface is implemented by all the bean factories that pre-loads their bean definitions to enumerate all their bean instances.
Spring Boot loads many beans into ApplicationContext on start up depends on the dependencies as per your pom. xml. You can call applicationContext. getBeanDefinitionNames() method to list all beans loaded into ApplicationContext.
Read about @Configurable
annotation that allows to configure beans using AspectJ:
If you don't want to use AspectJ, you could use the
ApplicationContext.getAutowireCapableBeanFactory().autowireBean()
method to configure beans that live outside the spring container. (see java docs).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With