Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting beans into a class outside the Spring managed context

Tags:

java

spring

I'm an end-user of one of my company's products. It is not very suitable for integration into Spring, however I am able to get a handle on the context and retrieve the required bean by name. However, I would still like to know if it was possible to inject a bean into this class, even though the class is not managed by Spring itself.

Clarification: The same application which is managing the lifecycle of some class MyClass, is also managing the lifecycle of the Spring context. Spring does not have any knowledge of the instance of MyClass, and I would like to some how provide the instance to the context, but cannot create the instance in the context itself.

like image 436
Spencer Kormos Avatar asked Nov 21 '08 21:11

Spencer Kormos


People also ask

How do you inject Spring bean into non Spring class?

To inject a bean into an unmanaged object, we must rely on the AnnotationBeanConfigurerAspect class provided in the spring-aspects. jar. Since this is a pre-compiled aspect, we would need to add the containing artifact to the plugin configuration.

How do you inject a bean class?

One way to bring a bean into Spring despite its manufacture being external is to use a helper class marked as a @Configuration bean that has a method (marked with @Bean ) that actually makes the instance and hands it back through Spring (which does its property injection and proxy generation at that point).


2 Answers

You can do this:

ApplicationContext ctx = ... YourClass someBeanNotCreatedBySpring = ... ctx.getAutowireCapableBeanFactory().autowireBeanProperties(     someBeanNotCreatedBySpring,     AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, true); 

You can use @Autowired and so on within YourClass to specify fields to be injected etc.

like image 156
David Tinker Avatar answered Oct 11 '22 17:10

David Tinker


One way to bring a bean into Spring despite its manufacture being external is to use a helper class marked as a @Configuration bean that has a method (marked with @Bean) that actually makes the instance and hands it back through Spring (which does its property injection and proxy generation at that point).

I'm not quite sure what scope you need; with prototype, you'll get a fresh bean in each place.

@Configuration public class FooBarMaker {     @Bean(autowire = Autowire.BY_TYPE)     @Scope("prototype")     public FooBar makeAFooBar() {         // You probably need to do some more work in here, I imagine         return new FooBar();     } } 

You can inject properties required for manufacture into the @Configuration bean. (I use this to create instances of an interface where the name of the class to instantiate is defined at runtime.)

like image 43
Donal Fellows Avatar answered Oct 11 '22 19:10

Donal Fellows