[英]Spring dependency injection with @Autowired annotation without setter
[英]Spring: Why is setter not called in spite of @Autowired annotation
我正在學習春天。 我將Spring與JDBC結合使用,並且還閱讀了有關自動裝配的信息。
所以我寫了這個
public class JdbcAccess {
@Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
System.out.println("setDataSource called");
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void getCount1() {
String sql= "SELECT COUNT(*) FROM MYTABLE";
jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(getDataSource());
int count = jdbcTemplate.queryForInt(sql);
System.out.println("Result is = " + count);
}
public void getCount2() {
String sql= "SELECT COUNT(*) FROM MYTABLE";
int count = jdbcTemplate.queryForInt(sql); // Line 66
System.out.println("Count = " + count);
}
}
我期望以下作為輸出:
setDataSource called
Count = 3
我得到的是:
Exception in thread "main" java.lang.NullPointerException at playwithspring.JdbcAccess.getCount2(JdbcAccess.java:66)
這意味着Spring不會調用setDataSource(..)
,但是Spring框架會正確設置數據源,因為對getDataSource()
進行調用的getCount1()
getDataSource()
運行良好。 所以我的問題是:
請注意:我運行getCount1()
或getCount2()
代替
場注入
@Autowired
private DataSource dataSource;
如果要調用設置器,請使用設置器注入而不是字段注入。
@Autowired
public void setDataSource(DataSource dataSource) {
System.out.println("setDataSource called");
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
發生異常的原因是因為未使用setDataSource
調用,因為Spring使用反射來設置數據源。
您有兩個不錯的選擇來設置它,或者用@Autowired注釋您的setter方法,或者可以將當前注釋保留在dataSource變量上,並使用@PostConstruct注釋初始化jdbcTemplate
,我認為這會導致代碼更jdbcTemplate
。
@Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
@PostConstruct
private void init() {
jdbcTemplate = new JdbcTemplate(dataSource);
System.out.println("jdbTemplate created");
}
public void getCount2() {
String sql= "SELECT COUNT(*) FROM MYTABLE";
int count = jdbcTemplate.queryForInt(sql);
System.out.println("Count = " + count);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.