何时使用限定符和配置文件标记

Lin*_*air 2 java spring

在Java Spring中,何时使用限定符标记与profile标记有意义?难道你不能使用任何一个,因为它们都是有条件的自动装配?使用其中一个或哪一个有什么好处或成本?

Mon*_*mul 8

@Qualifier:

可能存在这样一种情况:当您创建多个相同类型的bean并且想要仅使用属性连接其中一个bean时,在这种情况下,您可以使用@Qualifier注释和@Autowired通过指定哪个精确bean来消除混淆将有线.

假设你有两个spring组件类Toyota.class和Bmw.class都实现了一个接口Car.class

@Component
public class Toyota implements Car

@Component
public class Bmw implements Car
Run Code Online (Sandbox Code Playgroud)

现在,如果你想像这样自动装载汽车对象:

@Autowired
private Car car;
Run Code Online (Sandbox Code Playgroud)

会有一个混乱的春豆来电线,丰田还是宝马?因此弹簧容器会引发错误.这就是@Qualifier通过告诉容器确切地需要连接哪种汽车实施来拯救的地方.所以重新定义这样的代码:

@Component
@Qualifier("toyota")
public class Toyota implements Car

@Component
@Qualifier("bmw")
public class Bmw implements Car

@Autowired
@Qualifier("toyota")
private Car car;
Run Code Online (Sandbox Code Playgroud)

现在在布线过程中,弹簧容器确切地知道哪一个接线,丰田在这种情况下实施.这就是@Qualifier的作用.

@轮廓:

@Profile允许按条件注册bean.例如,根据在开发,测试,登台或生产环境中运行的应用程序注册bean.

在我们之前的示例中,假设我们希望在开发期间使用toyota实现并在测试期间使用bmw.所以重新定义下面的代码:

@Component
@Profile("test")
public class Toyota implements Car

@Component
@Profile("dev")
public class Bmw implements Car

@Autowired
private Car car;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我们不需要在布线期间指定@Qualifier.Spring容器将根据运行时配置文件连接正确的实现.

  • 使用 applicaiton.properties 文件,我们可以指定在运行时使用哪个配置文件,示例: spring.profiles.active=test (3认同)