Reputation: 87
I'm making a web app using spring, in web.xml I have defined context-param to look for application-context.xml file which scans for everything besides controllers and app-servlet.xml that scans only for controllers.
application-context.xml contains the datasource to the database and I inject the datasource in the daos like this:
@Autowired
DataSource dataSource;
Now if I try create a DAO by hand in the controller(I know i probably should use services for that, but it's just for test purposes for now) I get null pointer exception, however when I inject the DAO it loads properly.
So why does it happen? DAOs are not managed by the DI container only the datasource is, so why can't I create the dao by hand?
Upvotes: 0
Views: 34
Reputation: 309008
Spring bean factory and "new" are orthogonal: once you call "new", it's in your hands, not Spring's.
The situation you describe is common: You want Spring to manage bean lifecycle and dependencies in production, but when testing you want to do it yourself with mocks. My suggestion is to write your app to use Spring for DI and bean creation, but have constructors for manual injection of mocks when you test.
Upvotes: 2
Reputation: 160321
Yes; objects not under Spring's control are... well, outside of Spring's control.
There are some ways around this, e.g., allowing new
ed objects to get Spring DI (e.g., byte code manipulation).
Upvotes: 1