Let's say we have a class:
public class MyClass {
@Autowired private AnotherBean anotherBean;
}
Then we created an object of this class (or some other framework have created the instance of this class).
MyClass obj = new MyClass();
Is it possible to still inject the dependencies? Something like:
applicationContext.injectDependencies(obj);
(I think Google Guice has something like this)
Not without some workarounds, as Spring knows nothing about this instance.
The real question is: why are you creating instances of a class that you want dependencies injected into manually, rather than letting Spring control it? Why isn't the class using
MyClass
gettingMyClass
injected into it?Just got the same need and in my case it was already the logic inside non Spring manageable java class which had access to
ApplicationContext
. Inspired by scaffman. Solved by:You can also mark your MyClass with @Configurable annotation:
Then at creation time it will automatically inject its dependencies. You also should have
<context:spring-configured/>
in your application context xml.You can do this using the
autowireBean()
method ofAutowireCapableBeanFactory
. You pass it an arbitrary object, and Spring will treat it like something it created itself, and will apply the various autowiring bits and pieces.To get hold of the
AutowireCapableBeanFactory
, just autowire that:I wanted to share my solution that follows the
@Configurable
approach asbriefly
mentioned in @glaz666 answer becauseMy setup
Spring Neo4j & Aop starts
(which is irrelevant anyway)Spring Boot
is ready using@Configurable
approach (usingApplicationRunner
)Steps
I needed to follow the steps below in order to get it working
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE, dependencyCheck = false)
to be placed on top of yourBean
that is to be manually instantiated. In my case theBean
that is to be manually instantiated have@Autowired
services hence, the props to above annotation.XXXApplicaiton.java
(or the file that is annotated with@SpringBootApplication
) with the@EnableSpringConfigured
and@EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.ENABLED)
compile('org.springframework.boot:spring-boot-starter-aop')
andcompile('org.springframework:spring-aspects:5.0.7.RELEASE')
Bean
that is annotated with@Configurable
anywhere and its dependencies should be autowired.*In regards to point #3 above, I am aware that the
org.springframework.boot:spring-boot-starter-aop
transitively pulls thespring-aop
(as shown here mavencentral) but, in my case the Eclipse failed to resolve the@EnableSpringConfigured
annotations hence, why I explicitly added thespring-aop
dependency in addition to the starter. Should you face the same issue, just declare the dependency or go on adventure of figuring outorg.springframework.context.annotation.aspect.*
is not available