项目场景:
//父类
@Repository
public class BaseDao<T>{
private JDBCDataSourceByDruid jdbcDataSourceByDruid;
private QueryRunner q;
public BaseDao() {
}
@Autowired
public BaseDao(JDBCDataSourceByDruid jdbcDataSourceByDruid, QueryRunner q) {
this.jdbcDataSourceByDruid = jdbcDataSourceByDruid;
this.q = q;
}
}
//子类
@Repository
public class UserDao<T> extends BaseDao{
//获取连接工具类
JDBCDataSourceByDruid jdbcDataSourceByDruid;
//sql执行类
private QueryRunner queryRunner;
public UserDao() {
}
@Autowired
public UserDao(JDBCDataSourceByDruid jdbcDataSourceByDruid, QueryRunner queryRunner) {
this.jdbcDataSourceByDruid = jdbcDataSourceByDruid;
this.queryRunner = queryRunner;
}
问题描述
创建了个基础类BaseDao,设置了几个通用方法,其他Dao继承自BaseDao,子类DaO调用父类BaseDao方法的时候,父类的一些属性没有注入。
原因分析:
与父类的构造器注入有关,因为Spring或是jvm默认调用无参构造器,所以父类的构造器注入并没有注入,因为构造器注入用的是有参构造器
解决方案:
1、子类给父类传入需要的参数
@Autowired
public UserDao(JDBCDataSourceByDruid jdbcDataSourceByDruid, QueryRunner queryRunner) {
this.jdbcDataSourceByDruid = jdbcDataSourceByDruid;
this.queryRunner = queryRunner;
super.setJdbcDataSourceByDruid(jdbcDataSourceByDruid);
super.setQueryRunner(queryRunner);
}
2、父类直接在属性上注入(ps:没搞明白原理,不知道为什么就行)
//父类
@Repository
public class BaseDao<T>{
@Autowired
private JDBCDataSourceByDruid jdbcDataSourceByDruid;
@Autowired
private QueryRunner q;
}
其他知识:
1、父类构造器先于子类构造器创建
2、子类调用的实质是父类实例化好的方法