Naftuli Kay
Naftuli Kay

Reputation: 91790

Is it possible to autowire dependencies that are created outside of an ApplicationContext?

I've got an application which uses JAXRS to map Restlet resources using annotations. However, the only entry point I have is essentially defining a list of resource classes in the application configuration. These classes are instantiated by Restlet or JAXRS, so I have no way to put them in my ApplicationContext. Is there a way to have Spring scan the classpath and autowire new instances as necessary? I've already tried using something like below:

@Autowired
private SessionFactory sessionFactory;

Unfortunately, it doesn't really work. Is there a way to do what I'm talking about here?

Upvotes: 0

Views: 1407

Answers (2)

palto
palto

Reputation: 3583

You can use AspectJ to dependency inject your beans that are created out of your control, or if you create objects using new. You can read more on Springs documentation: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-using-aspectj

Essentially what you will do is add @Configurable annotation to the class that you want to be target of injection. You also have to enable it in Spring by having in your Spring xml. Lastly you have to decide between compile time weaving or runtime weaving. Again you can get help from spring documentation.

Loadtime weaving: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-aj-ltw

If you use maven you can check this Stackoverflow question for setting up compile time AspectJ: Why doesn't AspectJ compile-time weaving of Spring's @Configurable work?

Upvotes: 4

Bozho
Bozho

Reputation: 597324

ApplicationContext.getAutowireCapableBeanFactory().autowireBean(object) will inject all dependencies into the object.

Upvotes: 4

Related Questions