问题描述
使用Spring连接,如果我有多个接口实现,我可以使用@Qualifier来指定我想要的那个。
With Spring wiring, if I have multiple implementations of an interface, I can use @Qualifier to specify which one I want.
例如,假设我有一个
@Component
@Qualifier("Toyota")
public class Toyota implements Car
和
@Component
@Qualifier("Bmv")
public class Bmv implements Car
然后我可以选择具体的实现:
Then I can select a specific implementation with:
@Qualifier("Toyota") Car car
但有没有办法根据环境选择实施?
But is there a way to select the implementation based on an environment?
即如果我将spring.profiles.active设置为local,那么我将选择Car的'Toyota'实现,但如果spring.profiles.active设置为dev或stage,那么我将选择Car的'Bmv'实现?
I.e. if I have spring.profiles.active set to local, then I will select the 'Toyota' implementation of Car, but if spring.profiles.active is set to dev or stage, then I will select the 'Bmv' implementation of Car?
我们将赞赏确切语法的一个例子。
An example of the exact syntax would be appreciated.
推荐答案
啊,解决方案实际上非常简单:
Ah, the solution is actually quite simple:
@Component
@Qualifier("Bmv")
@Profile("!dev")
public class Bmv implements Car
和
@Component
@Qualifier("Toyota")
@Profile("dev")
public class Toyota implements Car
这样,汽车的布线将使用丰田开发环境,否则Bmv 。
This way, the wiring of Car will use Toyota for dev environment, and Bmv otherwise.
这篇关于弹簧布线以环境为条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!