How to use spring to resolve dependencies of a manually created object?

I would like to know if Spring can be used to resolve dependencies of an object created manually in my program. Take a look at the following class:

public class TestClass { private MyDependency md; public TestClass() { } ... public void methodThaUsesMyDependency() { ... md.someMethod(); ... } } 

This TestClass is not a Spring bean, but needs MyDependency, which is a Spring bean. Is there a way I can nest this dependency through Spring, even if I create a TestClass with a new statement inside my code?

thanks

+4
source share
3 answers

Edit: The method that I describe in my original answer below is a general way to execute the DI of an external container. For your specific need - testing - I agree with DJ's answer. It is much more appropriate to use Spring testing support, for example:

 @Test @ContextConfiguration(locations = { "classpath*:**/applicationContext.xml" }) public class MyTest extends AbstractTestNGSpringContextTests { @Resource private MyDependency md; @Test public void myTest() { ... 

While the above example is a TestNG test, Junit support in 8.3.7.2 is also supported . Contextual management and caching .


General approach: Annotate your class using @Configurable and use AspectJ load time or compile time. See 6.8.1 in the Spring AOP documentation for more details.

You can then annotate your instance variables with @Resource or @Autowired . Although they fulfill the same goal of dependency injection, I recommend using @Resource , as it is a Java standard, not a Spring-specific one.

Finally, be sure to consider the transient keyword (or @Transient for JPA) if you plan on serializing or saving objects in the future. Most likely, you do not want to serialize links to your DI'd repository, service, or beans component.

+3
source

See the autowire () method in the AutowireCapableBeanFactory class. If you are using ClasspathXmlApplicationContext , you can get factory with getAutowireCapableBeanFactory ()

To get the ApplicationContext, you will need to use a static singleton or another central repository such as a JNDI or Servlet container. See DefaultLocatorFactory for how to get an ApplicationContext instance.

+2
source

If you need testing, Spring has good support for the above scenario.

Check Out Spring Testing Reference Guide

+1
source

All Articles