I want to avoid coupling my application classes to
ApplicationContext. In the past, I did this by creating a wrapper around it that exposed type-safe getter methods for the service objects I was interested in. But I'm starting a new project with Spring 2.5 now, and I'm thinking it would be much nicer not to have to deal with the wrapper and just let Spring inject dependencies into my "main" classes--or, more precisely,
instances of my "main" classes. Clearly, the Spring team has given this some thought because they built support for just this kind of injection for integration tests. I'm trying to achieve the same thing, but for a command line utility instead of a test.
I played around with @Configurable, but can't get it to work. Apparently, it requires some AspectJ configuration including a runtime agent that I have to load with the JVM...? Ugh. I don't know much about AspectJ. Here's what I've got:
Code:
@Configurable
public class HelloWorld {
@Autowired
private IDataAccessObject m_dao;
public static void main(String[] args) {
// This just creates a singleton app context via
// a DefaultLocatorFactory.
DependencyInjection.bootstrap();
// Now do some stuff!
new HelloWorld().doStuff();
}
public void doStuff() {
// I wish this worked, but it just throws a NPE.
List<Object> result = m_dao.runSomeQuery(); // NPE!
}
}
I would be just as happy if I could pass in an already-constructed instance of my class to Spring and say, "Okay, here's an object. Now wire it up!"