Reputation: 603
I try use IoC without xml. But I don't understand why @Autowired workin in the first case, and doesn't work in second case: I have 3 classes:
@Configuration
public class DataSourceBean{
@Bean
public DataSource dataSource(){
DataSource ds = new DataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://192.168.1.99:3306/somethink");
ds.setUsername("devusr");
ds.setPassword("root");
ds.setInitialSize(5);
ds.setMaxActive(10);
ds.setMaxIdle(5);
ds.setMinIdle(2);
return ds;
}
}
public class AbstractDao {
@Autowired
private DataSource dataSource;
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public AbstractDao(){
System.out.println("dataSource = " + dataSource);
}
}
and
@RestController
public class PageController {
@Autowired
private DataSource dataSource;
private AbstractDao dao;
@RequestMapping(value = "/test" , method = RequestMethod.GET)
public String homePage(){
// System.out.println("$$ dataSource = " + dataSource);
AbstractDao dao = new AbstractDao();
return "";
}
}
and in a PageControllers autowiring works properly, I see that it doesn't null. And when I create new AbstractDao autowired doesn't work and dataSourse == null . I try add some annotations to class AbstractDao, but it doesn't work. what am I doing wrong? and how I must do it properly? Thanks
Upvotes: 0
Views: 28
Reputation: 584
In your PageController you have to inject AbstractDao. Autowiring does not work when instantiating Objects with new operator. Try this instead in your PageController:
@RestController
public class PageController {
@Autowired
private DataSource dataSource;
@Autowired
private AbstractDao dao;
@RequestMapping(value = "/test" , method = RequestMethod.GET)
public String homePage(){
// System.out.println("$$ dataSource = " + dataSource);
return "";
}
}
Upvotes: 1