【问题标题】:Provide different constructor arguments to a common dependency based on dependant class基于依赖类为公共依赖提供不同的构造函数参数
【发布时间】:2015-11-03 08:52:57
【问题描述】:

我正在使用 Spring Boot 并使用注释对其进行配置。假设我有以下课程:

@FunctionalInterface
@Component
public interface VerificationStrategy {
    void verify(Foo foo) throws Exception;
}

@Component
public class A {
    @Autowired
    public A(VerfificationStrategy assumption) {}
}

@Component
public class B {
    @Autowired
    public B(A a) {}
}

@Component
public class C {
    @Autowired
    public C(A a) {}
}

现在我想实现的目标:

  • B 的实例应接收具有VerificationStrategy 的一种实现的 A 实例

  • C 的实例应该接收 A 的实例以及 VerificationStrategy 的其他一些实现

使用注释实现这一目标的最优雅、最有效的方法是什么?

【问题讨论】:

    标签: java spring spring-boot java-8


    【解决方案1】:

    AFAIK 这在 Spring 中是不可能的。您需要创建 A 类的两个实现。

    但你可以这样做:

    @FunctionalInterface
    public interface VerificationStrategy {
        void verify(Foo foo) throws Exception;
    }
    
    @Configuration
    public class VerificationConfiguration {
        @Bean
        public VerificationStrategy strategy1() {
            return (foo) -> {System.out.println(foo);};
        }
    
        @Bean
        public VerificationStrategy strategy2() {
            return (foo) -> {System.out.println(foo);};
        }
    }    
    
    @Component
    public class B {
        @Autowired
        public B(@Qualifier("strategy1") VerificationStrategy a) {}
    }
    
    @Component
    public class C {
        @Autowired
        public C(@Qualifier("strategy2") VerificationStrategy a) {}
    }
    

    【讨论】:

    • 这满足了我对优雅解决方案的要求。
    猜你喜欢
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 2015-09-20
    • 2021-08-14
    • 1970-01-01
    • 2012-03-19
    • 2012-08-19
    • 1970-01-01
    相关资源
    最近更新 更多