具有两层以上的Spring autowire优先级

时间:2016-08-27 18:21:33

标签: java spring

我怎么能多次覆盖自动装配的bean?考虑这个3层结构:

库1 定义了一个接口和一个默认实现。

public interface Foo {}

@Component
public class FooImpl1 implements Foo {}

在所有3层中,该接口将用于自动装配。

@Autowired
private Foo foo;

库2 依赖于库1,并提供自己的实现,必须覆盖第一个,即自动装入库1的现有代码。

@Component
public class FooImpl2 implements Foo {}

实际的应用程序依赖于库2,还提供了另一种必须覆盖前者的实现。

@Component
public class FooImpl3 implements Foo {}

如何配置?如果只有两个图层,我可以使用@Primary,但这不适用于两个以上的图层,因为@Primary无法再次覆盖。是否有一种更细粒度的方法可以优先考虑我忽略的bean,或者我可以使用@Configuration完成第二次覆盖,或者你不能多次覆盖bean,我不得不求助于某种静态助手如FooProvider.getFoo()而不是自动装配?

1 个答案:

答案 0 :(得分:0)

可能不是这种情况,但是当你有多个实现并希望建立某种排序时,请注释注释@order

@order(3)
@Component
public class FooImpl1 implements Foo {}

@order(1)
@Component
public class FooImpl2 implements Foo {}

@order(2)
@Component
public class FooImpl3 implements Foo {}

public class PrintFoo {

List<Foo> fooList;

@autowired
public PrintFoo() {
for(Foo fooImpl: fooList) {
            System.out.println(fooImpl.getClass().getSimpleName());
        }
}

输出应为:

  1. FooImpl2
  2. FooImpl3
  3. FooImpl1
相关问题