2

让我用代码演示一下:

public interface A {
  ....
}

@Profile({"V1"})
@Component
public class B implements A {
....
}

@Profile({"V2"})
@Component
public class C implements A {
....
}

我如何动态地(在每个到达的请求上)使 spring 根据它们的配置文件自动装配上述类之一?甚至可以在接线时做这样的事情吗?

背景:我正在寻求一种实现服务器端版本控制机制的好做法。如果请求属于版本“V1”,我想用“V1”配置文件自动装配一个类,反之亦然。(目前我正在自动装配一个列表并迭代它们以找到合适的版本)。

4

4 回答 4

2

甚至可以在每个请求中自动装配 bean 吗?

不,这是不可能的。创建上下文时注入 Bean。

我正在寻求一种实现服务器端版本控制机制的好习惯

您可以按照这个答案How to manage REST API versioning with spring?

于 2015-05-03T06:00:21.537 回答
1

答案是否定的,因为当您尝试在 spring 中激活多个配置文件 -Dspring.profiles.active=profile1,profile2并且两个配置文件都包含 bean 时,implements Aspring 将使用 bean 的最后一个活动定义,implements AB在您的情况下。

于 2015-05-03T05:35:40.917 回答
0
public interface A {
  ....
}

@Profile({"V1"})
@Service("bean1")
public class B implements A {
....
}

@Profile({"V2"})
@Service("bean2")
public class C implements A {
....
}

现在是第三课:

class D {
@Autowired
@Qualifier("bean1")
private A a;

}

我希望能帮助你

于 2015-05-03T06:22:01.373 回答
-2

您在要注入上述接口的地方使用 @Qualifier 注释

于 2015-05-03T05:37:38.387 回答