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