Anand B
Anand B

Reputation: 3085

@Autowired in bean not in spring context

I am new to springs. Is there an alternative for autowired to be used in a ordinary java bean which is not present in spring context.

Upvotes: 0

Views: 773

Answers (1)

Bhashit Parikh
Bhashit Parikh

Reputation: 3131

You can do so by using Spring @Configurable with some AspectJ magic.

If you need a detailed explanation, here is the link.

And here is a brief overview of how it can be achieved.

First you have some bean that you want injected somewhere:

@Component
public class InjectedClass {
    // ...
}

Then, you have a class that is not spring-container managed, that you want to instantiate. You want autowiring to work with this class. You mark it as a @Configurable.

@Configurable
public class NonContainerManagedClass  {

    @Autowired
    private InjectedClass injected;

    // ...
}

Now you need to tell spring that you want this non-container managed autowiring to work. So you put the following in your spring configuration.

<context:load-time-weaver />
<context:spring-configured />

Now, since this kind of thing requires modification of the bytecodes of your @Configurable class. So you tell Tomcat to use a different classloader. You can do so by creating a context.xml in your application's META-INF diretory and putting the following in there.

<Context path="/youWebAppName">
    <Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"
        useSystemClassLoaderAsParent="false"/>
</Context>

Now, Tomcat needs to find that classloader. You can ensure that by putting Spring's spring-tomcat-weaver.jar (probably named org.springframework.instrument.tomcat-<version>.jar) in your tomcat installation's lib directory, and voila, the aspectj magic starts working. For classes that are annotated with @Configurable annotation, the @Autowired dependencies are resolved automatically; even if the instances are created outside of the spring-container.

This is probably the only way to make that work with Spring, in a clean manner. Make sure that you have appropriate dependencies in your classpath.

Another way would be to use the full AspectJ functionality and providing custom aspects around all your constructors and handling the dependency-injection yourself.

Upvotes: 1

Related Questions