方法一
通过 super.setBaseDao方法设置父类私有变量
父类
public class BaseServiceImpl {
private BaseDao baseDao;
public BaseDao getBaseDao() {
return baseDao;
}
public void setBaseDao(BaseDao baseDao) {
this.baseDao = baseDao;
}
public void test(){
System.out.println("TsetService...... ");
baseDao.test();
}
}
子类
@Service("testServiceImpl")
public class TestServiceImpl extends BaseServiceImpl{
@Resource(name="testDao")
public void initBaseDao(TestDao testDao) {
super.setBaseDao(testDao);
}
}
方法二
@PostConstruct是Java EE 5引入的注解,Spring允许开发者在受管Bean中使用它。当DI容器实例化当前受管Bean时,@PostConstruct注解的方法会被自动触发,从而完成一些初始化工作
父类同上
子类
@Service("testServiceImpl")
public class TestServiceImpl extends BaseServiceImpl{
private TestDao testDao;
public TestDao getTestDao() {
return testDao;
}
@Resource(name="testDao")
public void setTestDao(TestDao testDao) {
this.testDao = testDao;
}
@PostConstruct
public void initBaseDao(TestDao testDao) {
super.setBaseDao(testDao);
}
}
方法三
父类被注入对象非私有,子类重写setter方法注入到父类变量
父类
public class BaseServiceImpl {
protected BaseDao baseDao;
public BaseDao getBaseDao() {
return baseDao;
}
public void setBaseDao(BaseDao baseDao) {
this.baseDao = baseDao;
}
public void test(){
System.out.println("TsetService...... ");
baseDao.test();
}
}
子类
@Service("testServiceImpl")
public class TestServiceImpl extends BaseServiceImpl{
@Resource(name="testDao")
public void setBaseDao(BaseDao baseDao) {
this.baseDao = baseDao;
}
}
spring使用注解通过子类注入父类的私有变量