设置某个配置文件时不加载Spring bean [英] Not loading a Spring bean when a certain profile is set

查看:2046
本文介绍了设置某个配置文件时不加载Spring bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:所以,我有几个bean连接外部系统。对于开发,可以方便地模拟外部系统并将接口bean替换为产生或多或少静态响应的一些实现。所以我一直在做的是创建一个接口,真正的实现和这样的存根实现:

Background: So, I've got several beans that interface external systems. For development, it's convenient to mock the external systems and replace the interfacing beans with some implementations that produce more or less static responses. So what I've been doing is to create an interface, the real implementation and a stub implementation like this:

public interface ExternalService {
// ...
}

@Service
public class ExternalServiceImpl implements ExternalService {
// ...
}

@Service
@Primary
@Profile({"stub"})
public class StubExternalService implements ExternalService {
// ...
}

...这很有效:如果存根配置文件不存在,则存根 - bean根本没有加载。如果它存在,它很好地取代了真正的实现,因为@Primary注释。

...and this works great: if the stub profile is not present, the stub-bean does not get loaded at all. If it is present, it nicely supersedes the real implementation because of the @Primary annotation.

问题:然而,现在,我已经运行了这是我第一次真正实现了两个相同界面的实现。其中一个被定义为主要,但另一个也可以通过从应用程序上下文加载它来使用。

Problem: Now, however, I've run for the first time in a situation where I've actually got two real implementations of the same interface. One of them is defined as primary, but the other may also be used by loading it from the application context.

我仍然想创建一个存根服务来替换它他们两个,但这次我将存根定义为@Primary的旧方法不起作用,因为已经有一个主要实现。基本上我需要的是在设置存根配置文件时不加载主bean的方法,但是我对如何做到这一点感到很遗憾。 Web搜索或其他Stack Overflow问题似乎没有帮助。

I'd still like to create a stub service to replace them both, but this time my old way of defining the stub as @Primary doesn't work, because there's already one primary implementation. Basically what I'd need is a way of not loading the primary bean when the stub profile is set, but I'm at loss on how exactly to do that. Web searches or other Stack Overflow questions don't seem to be helping.

推荐答案

原来答案非常简单:你添加在个人资料名称前面的非运营商():

Turns out the answer was surprisingly simple: you add a not-operator (!) in front of the profile name:

@Service
@Primary
@Profile({"!stub"})
public class ExternalServiceImpl implements ExternalService {
// ...
}

这种方式只在存根时加载bean - 个人资料无效。 Spring 3.2 M1 中添加了对此功能的支持。

This way the bean is only loaded when the stub-profile is not active. The support for this feature was added in Spring 3.2 M1.

但有一点需要注意:如果你写 @Profile({!stub,foo}),逗号将被视为或,而不是和。因此,如果 stub 未激活或 foo 处于活动状态,则会激活此示例bean。

There's one caveat, though: if you write @Profile({"!stub", "foo"}), the comma is treated as "or", not "and". So this example bean would be activated either if stub was not active or if foo was active.

这篇关于设置某个配置文件时不加载Spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆