java - 如何在父类(super class)中重用@Autowired bean?

标签 java spring oop autowired

我当前的项目有两个服务:

@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。我有两个解决方案:

  1. private OtherService otherService 更改为 protected OtherService otherService。但是考虑使用 @Autowired bean protected 不是一个好习惯吗?
  2. @Autowried private OtherService otherService;添加到ChildService

对于这种情况,有什么更好的建议吗?

最佳答案

已编辑。

将 OtherService 的访问说明符更改为 protected 或提供一个 DefaultService 中 protected getOtherService() 方法。

关于java - 如何在父类(super class)中重用@Autowired bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40045254/

相关文章:

Java - 如何扫描 token 并检查该 token 是否存在且是否为 double

java - Spring mvc 抛出 org.springframework.web.HttpMediaTypeNotAcceptableException : Could not find acceptable representation

php - 依赖倒置和接口(interface)

Spring Security LDAP 配置

java - 如何在@WebMvcTest测试中忽略@EnableWebSecurity注释的类

javascript - OOP:属于一个类和继承的计数器

php - 配置对象中的属性链接和 isset

java - 使用 Jackson 将 JSON 字符串转换为 Java 映射时出错

java - 如何通过节点客户端(而不是通过传输)在 Elasticsearch 中设置路径(path.home)

java - IDEA Groovy 测试类已经存在