Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access spring beans from objects not created by spring [duplicate]

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?

like image 372
Dev Blanked Avatar asked Oct 10 '13 17:10

Dev Blanked


People also ask

How do I get Spring bean in non Spring class?

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.

How do you get loaded beans in the Spring?

In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.

How can I see all the beans created?

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.

How can we get list of all beans used in Spring application?

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.


1 Answers

Read about @Configurable annotation that allows to configure beans using AspectJ:

  • Spring reference
  • Spring blogs

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).

like image 164
Jose Luis Martin Avatar answered Sep 20 '22 16:09

Jose Luis Martin