Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to know if it's possible to use Spring to resolve the 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, that is a spring bean. Is there some way I can inject this dependency through Spring, even if I instantiate TestClass with a new operator inside my code?

Thanks

like image 708
Alexandre Avatar asked Nov 26 '09 18:11

Alexandre


1 Answers

Edit: The method I'm describing in my original answer below is the general way to accomplish DI external of the container. For your specific need - testing - I agree with DJ's answer. It's much more appropriate to use Spring's test 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, there is also Junit support explained in 8.3.7.2. Context management and caching.


General approach: Annotate your class with @Configurable and utilize AspectJ load-time or compile-time weaving. See 6.8.1 in the Spring documentation on AOP for more details.

You can then annotate your instance variables with @Resource or @Autowired. Though they accomplish the same goal of dependency injection, I recommend using @Resource since it's a Java standard rather than Spring-specific.

Lastly, remember to consider using the transient keyword (or @Transient for JPA) if you plan on serializing or persisting the objects in the future. Chances are you don't want to serialize references to your DI'd repository, service, or component beans.

like image 134
Robert Campbell Avatar answered Nov 01 '22 16:11

Robert Campbell