java - Spring - 多个配置文件处于 Activity 状态

标签 java spring

我基本上在 Spring 中有一个 bean,我只想在 2 个配置文件处于 Activity 状态时激活它。基本上,它会是这样的:

@Profile({"Tomcat", "Linux"})
public class AppConfigMongodbLinux{...}

@Profile({"Tomcat", "WindowsLocal"})
public class AppConfigMongodbWindowsLocal{...}

所以我希望当我使用 -Dspring.profiles.active=Tomcat,WindowsLocal 时,它会尝试仅使用 AppConfigMongodbWindowsLocal,但它仍然会尝试注册AppConfigMongodbLinux

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appConfigMongodbLinux': Injection of autowired dependencies failed

是否可以仅在两个配置文件都处于 Activity 状态或我使用不正确时才注册 bean? :)

谢谢!!


编辑:发布完整堆栈。

错误实际上是在属性上缺少的属性上,但是这个 bean 会被激活吗?我想了解这一点,以确保我没有激活错误的 bean..

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
    ...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appConfigMongodbLinux': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.Integer mycompany.config.AppConfigMongodbLinux.mongoPort; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'mongo.port' in string value "${mongo.port}"
    ... 40 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.Integer mycompany.config.AppConfigMongodbLinux.mongoPort; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'mongo.port' in string value "${mongo.port}"
    ...
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'mongo.port' in string value "${mongo.port}"

最佳答案

Spring 5.1 版 及更高版本提供了用于指定更复杂的配置文件字符串表达式的附加功能。在您的情况下,可以通过以下方式实现所需的功能:

@Profile({"Tomcat & Linux"})
@Configuration
public class AppConfigMongodbLinux {...}

请阅读 Using @Profile Spring 引用文档中的章节以获取更多信息。

更新(方法级配置文件表达式): 实际上我已经测试了一些@Bean 方法级别的配置文件表达式,并且一切都像一个魅力:

/**
 * Shows basic usage of {@link Profile} annotations applied on method level.
 */
@Configuration
public class MethodLevelProfileConfiguration {

    /**
     * Point in time related to application startup.
     */
    @Profile("qa")
    @Bean
    public Instant startupInstant() {
        return Instant.now();
    }

    /**
     * Point in time related to scheduled shutdown of the application.
     */
    @Bean
    public Instant shutdownInstant() {
        return Instant.MAX;
    }

    /**
     * Point in time of 1970 year.
     */
    @Profile("develop & production")
    @Bean
    public Instant epochInstant() {
        return Instant.EPOCH;
    }
}

集成测试:

/**
 * Verifies {@link Profile} annotation functionality applied on method-level.
 */
public class MethodLevelProfileConfigurationTest {

    @RunWith(SpringRunner.class)
    @ContextConfiguration(classes = MethodLevelProfileConfiguration.class)
    @ActiveProfiles(profiles = "qa")
    public static class QaActiveProfileTest {

        @Autowired
        private ApplicationContext context;

        @Test
        public void shouldRegisterStartupAndShutdownInstants() {
            context.getBean("startupInstant", Instant.class);
            context.getBean("shutdownInstant", Instant.class);

            try {
                context.getBean("epochInstant", Instant.class);
                fail();
            } catch (NoSuchBeanDefinitionException ex) {
                // Legal to ignore.
            }
        }
    }

    @RunWith(SpringRunner.class)
    @ContextConfiguration(classes = MethodLevelProfileConfiguration.class)
    @ActiveProfiles(profiles = {"develop", "production"})
    public static class MethodProfileExpressionTest {

        @Autowired
        private ApplicationContext context;

        @Test
        public void shouldRegisterShutdownAndEpochInstants() {
            context.getBean("epochInstant", Instant.class);
            context.getBean("shutdownInstant", Instant.class);

            try {
                context.getBean("startupInstant", Instant.class);
                fail();
            } catch (NoSuchBeanDefinitionException ex) {
                // Legal to ignore.
            }
        }
    }
}

Spring 5.1.2 版本已测试。

关于java - Spring - 多个配置文件处于 Activity 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38133808/

相关文章:

spring - 无法启动 Spring Boot 应用程序 NoClassDefFoundError

java - 出现错误 404 源服务器未找到目标资源的当前表示或不愿意透露该表示存在

java - 如何强制 Java Applet 从缓存中加载

java - 如何从xml中提取参数?

Java 没有将准确的日期存储到 mysql 数据库

java - 使用@Transactional时EntityManager.persist()不插入数据

java - 从上到下打印整数的 ArrayList 并将每个元素作为字符串返回

java - Log4j:带有属性的配置回退错误处理程序

java - Spring:为什么在每个测试类结束时不调用@PreDestroy?

java - 在 Spring Controller 中同时执行两种方法时只有一次数据获取的最佳方法