繁体   English   中英

春季:为何尽管使用@Autowired批注仍未调用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()运行良好。 所以我的问题是:

  • 那么Spring如何在不调用setter的情况下设置dataSource
  • 我可以在上述程序中做什么 以实现所需的输出

请注意:我运行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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM