在一期财务项目中,一个子类业务对象和父类业务对象同时注入同一个属性时,如果子类调用父类中某一个方法,如果该父类的方法引用了之前注入的属性,该属性是被子类覆盖的,也就是说在父类的上下文中,该属性是空的,暂且先不考虑代码的规范性,先通过一个简单的demo说明该问题点
1、子类和父类同时注入的对象 ResourceManager
public class ResourceManager {
public void resourceSystem(){
System.out.println("resource");
}
}
2、父类
public class ParentService {
private ResourceManager resourceManager;
public void print(){
resourceManager.resourceSystem();//应该是空值
System.out.println("parent");
}
public void setResourceManager(ResourceManager resourceManager) {
this.resourceManager = resourceManager;
}
}
3、子类
public class ChildService extends ParentService {
private ResourceManager resourceManager;
public void print(){
resourceManager.resourceSystem();
super.print(); //调用父类方法
System.out.println("child");
}
public void setResourceManager(ResourceManager resourceManager) {
this.resourceManager = resourceManager;
}
}
简单的测试方法
public class CrmTest extends TestCase {
ApplicationContext context = new ClassPathXmlApplicationContext("spring/spring.xml");
public void testABC(){
ChildService childService = (ChildService) context.getBean("child");
childService.print();
}
}
通过红色的字说明了问题点
本身这种编码是不规范的,但是在项目中没有定期的review代码,导致线上出现了这个问题,值得每个PM深思