以 spring 读取数据库为例, 配置文件spring-bean.xmlspring
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">sql
<property name="driverClassName" value="${jdbc.driverClassName}"/>数据库
<property name="url" value="${jdbc.url}"/>app
<property name="username" value="${jdbc.username}"/>this
<property name="password" value="${jdbc.password}"/>url
</bean>.net
服务类xml
@Serviceget
public class ProductService {it
@Autowired // 这里的注入是没问题的
private ProductDao productDao;
public static Product getByBarCode(String barCode) {
// 注意这是一个静态方法, 是不能使用上面productDao类变量的
ProductDao pdDao = new ProductDao();
return pdDao.getByBarCode(barCode);
}
数据处理类
public class ProductDao implements IProductDao {
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
public Product get(String sql, SqlParameterSource namedParameters) {
Product reObj;
try {
reObj = this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, new BeanPropertyRowMapper<Product>(Product.class));
} catch (EmptyResultDataAccessException e) {
return null;
}
}
@Autowired注解是没法用于static方法的.间接使用可能不报错, 但没法取得spring注入的内容. 好比上例一个service的static方法 new 了一个 dao, 这个 dao 中感受应注入的内容就没有被注入.
上例表现为在setDataSource方法中, 断点观察namedParameterJdbcTemplate能够取到数据, 但在get方法中namedParameterJdbcTemplate老是null.
这个错误比较隐蔽, 因此在spring有注入的场合应避免使用 static 方法.