gpt4 book ai didi

java - 如果 Spring 配置文件与指定的配置文件不同,如何使用注释 @Profile 跳过服务类

转载 作者:行者123 更新时间:2023-11-30 03:57:35 25 4
gpt4 key购买 nike

我有一个标有注释的服务类:

@Service(value="myService")
@Profile("test")
public class MyServiceImpl implements MyService{
...
}

因此,如果当前的 Spring 配置文件是“test”,则此类的方法将用于服务 myService。同时,我还希望有另一个具有相同注释的类,可能带有 @Profile("!test") ,当配置文件未测试时,在所有其他情况下加载该类,
如何在 .xml Spring 配置文件中不配置任何内容的情况下做到这一点?我想使用简单的注释。

最佳答案

您需要像这样定义另一个 bean:

@Service(value="myServiceDefault")
public class MyServiceImpl implements MyService{
..

}

然后将测试配置文件的初始代码更改为:

@Service(value="myService")
@Profile("test")
@Primary
public class MyServiceImpl implements MyService{
...
}

它的作用是注册一个实现供所有配置文件使用,然后当测试配置文件处于 Activity 状态时,由于 @Primary 注释而使用其他实现

如果您使用 Spring 4,您可以使用 @Conditional 注释提出更精细的配置策略

关于java - 如果 Spring 配置文件与指定的配置文件不同,如何使用注释 @Profile 跳过服务类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22760985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com