我当前的项目有两个服务:
@Service
public class OtherService{
}
interface IService{
void methodA();
void methodB();
void methodC();
}
@Service
public class DefaultService implement IService{
@Autowried
private OtherService otherService;
public void methodA(){...};
public void methodB(){...};
public void methodC(){...};
}
在实现其他功能时,我添加了新的业务流程:
- 想复用methodA,methodB
- 在新流程中运行 methodC 时添加新规则
所以我的解决方案是创建 new ChildService extends DefaultService
并覆盖 methodC
。
@Service
public class ChildService extends DefaultService{
@override
public void methodC(){
//want to use some method of otherService
}
}
问题是 methodC
想在父类中使用 otherService
bean。我有两个解决方案:
- 将
private OtherService otherService
更改为protected OtherService otherService
。但是考虑使用@Autowired
beanprotected
不是一个好习惯吗? - 将
@Autowried private OtherService otherService;
添加到ChildService
对于这种情况,有什么更好的建议吗?
最佳答案
已编辑。
将 OtherService 的访问说明符更改为 protected 或提供一个 DefaultService 中 protected getOtherService() 方法。
关于java - 如何在父类(super class)中重用@Autowired bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40045254/