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.
source share