7

我有两个豆子。两者都实现了邮寄功能。一个只有在部署到应用服务器时才有效。另一个用于测试。

我们有每个开发人员和环境的配置文件。我只想在实际测试时连接测试bean。不测试时应使用其他 bean。我该如何存档?

@Component
@Profile("localtest")
public class OfflineMail implements Mailing {}

解决办法:

使用“默认”我在某处读到了这个,但对于像“dev”这样的配置文件似乎没有回退到“默认”:

@Component
@Profile("default")
public class OnlineMail implements Mailing {}

-> 找不到用于接线的 bean 的异常。

留下个人资料:

@Component
public class OnlineMail implements Mailing {}

-> 运行“localtest”配置文件时抛出一个独特的异常。

添加所有配置文件:

@Component
@Profile("prod")
@Profile("integration")
@Profile("test")
@Profile("dev1")
@Profile("dev2")
@Profile("dev3")
...
public class OnlineMail implements Mailing {}

这实际上是有效的,但是我们的开发人员没有编号,他们使用“dev<WindowsLogin>”并添加配置文件,可能适用于一个 bean,但是当将它用于多个 bean 时会遇到麻烦,因为这肯定会变得丑陋。

使用 @Profile("!localtest") 之类的东西似乎也不起作用。

有谁知道更好的方法来获得“如果没有找到特定的 bean,则默认情况下获取电线”?

4

3 回答 3

10

我终于找到了一个简单的解决方案。

在线邮件默认是有线的。

@Component
public class OnlineMail implements Mailing {}

使用@Primary注释,离线邮件优先于在线邮件并避免了唯一异常。

@Component
@Profile("localtest")
@Primary
public class OfflineMail implements Mailing {}
于 2013-03-10T11:09:24.100 回答
2

试试这个:

@Component
@Profile("production")
public class OnlineMail implements Mailing {}

@Component
@Profile("localtest")
public class OfflineMail implements Mailing {}

然后使用@ActiveProfiles("localtest") 运行测试并使用“production”作为默认配置文件运行生产环境。

另外我希望在 Spring 的下一个版本中ActiveProfilesResolver引入SPR-10338 - 它可能对你有帮助(避免“dev1”、“dev2”等)。

于 2013-03-05T14:08:35.310 回答
0

Spring 非常支持 @Profile 注入 Bean:

interface Talkative {
    String talk();
}

@Component
@Profile("dev")
class Cat implements Talkative {
        public String talk() {
        return "Meow.";
    }
}

@Component
@Profile("prod")
class Dog implements Talkative {
    public String talk() {
        return "Woof!";
    }
}

在单元测试中工作

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContex-test.xml"})
@ActiveProfiles(value = "dev")
public class InjectByDevProfileTest
{
    @Autowired
    Talkative talkative;

    @Test
    public void TestTalkative() {
        String result = talkative.talk();
        Assert.assertEquals("Meow.", result);

    }
}

在 Main() 中工作:

@Component 公共类主 {

        public static void main(String[] args) {
            // Enable a "dev" profile
            System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
            ApplicationContext context =
                    new ClassPathXmlApplicationContext("applicationContext.xml");
            Main p = context.getBean(Main.class);
            p.start(args);
        }

        @Autowired
        private Talkative talkative;

        private void start(String[] args) {
            System.out.println(talkative.talk());
        }
    }

检查演示代码:https ://github.com/m2land/InjectByProfile

于 2016-05-13T12:52:48.083 回答