spring - 使用空字符串作为属性的默认值,以便可以将其与其他字符串连接以形成值

标签 spring application.properties

在我的 application.properties 文件中,我有以下由连接 3 个属性组成的属性:

eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:}

我的意图是,当变量属性未初始化时,eureka.instance.appname 应通过连接变量属性的默认空字符串来形成,以便该值将为 ${spring.application.name}${spring .profiles.active} 单独。

但是如果我按照上面指定的格式定义它,最终的字符串将无法正确形成。我找不到将空字符串指定为变体默认值的方法。 当我使用 ${variant:''} 时,当 spring.application.name 是 SERVICE 且 spring.profiles.active 是 DEV 并且变量未分配值时,选择默认值 ' ,我得到一个 eureka.instance.appname作为 SERVICEDEV''。

到目前为止我尝试过的:

eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:} 

不工作并且可能崩溃。

eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:''} 

给出 SERVICEDEV'',其中 spring.application.name 是 SERVICE,spring.profiles.active 是 DEV,并且变量未分配值

最佳答案

eureka.instance.appname=${spring.application.name}${spring.profiles.active}${variant:} 这对我有用。

其他方式:您可以让您的PropertySourcesPlaceholderConfigurer检查变体的值。如果为 null 则可以将其更改为空字符串。

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer() {

            @Override
            public void setEnvironment(Environment environment) {
                if (environment instanceof ConfigurableEnvironment && environment.getProperty("variant") == null) {
                    ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
                    env.getPropertySources().addLast(new MapPropertySource("Public key default", Collections.singletonMap("variant", "")));
                }

                super.setEnvironment(environment);
            }
        };
    }

关于spring - 使用空字符串作为属性的默认值,以便可以将其与其他字符串连接以形成值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56565097/

相关文章:

spring-boot-maven-plugin build-info.properties

spring - 使用 spring-cloud-vault 访问保管库 secret 并在 application.properties 中使用它

java - 创建并使用 loadUserByEmail 而不是 loadUserByUsername

java - 如果我在 MyBatis 的 <resultMap> 中定义 <association>,即使属性与列名匹配,我是否也必须定义所有字段?

java - Hibernate + MySQL 报告数据的最佳实践

java - 使用 Java 客户端实现 Spring Security

java - Spring Boot 无法从数据源确定 jdbc url

java - Spring的application.properties中添加环境变量

java - application.properties 中的注释

java - Servlet "newspring"不可用