【问题标题】:@value in spring boot not giving value from application.properties春季启动中的@value没有从application.properties中提供价值
【发布时间】:2021-05-23 04:37:07
【问题描述】:

我正在尝试将应用程序属性中的值读取到带有注释的类中

@Configuration
public class testClass {

  @Value("${com.x.y.z.dummy.name}")
  private String name;

一旦我在这个类中用@Bean注解的方法运行代码:

  @Bean
  public Helper helper(X x){
     System.out.println(this.name);
  }
        

这里的输出是 -> ${com.x.y.z.dummy.name} 而不是 application.properties 中 ${com.x.y.z.dummy.name} 的值。我尝试了@Autowired 并尝试从环境变量中读取。不确定会发生什么。有人可以帮忙吗? 添加application.properties:

com.x.y.z.dummy.name=localhost
com.x.y.z.dummy.host=8888

【问题讨论】:

  • 如果它是一个 Spring Boot 应用程序,它应该可以正常工作。如果它是 Spring Core 应用程序,则应将 PropertySourcesPlaceholderConfigurer 注册为 bean 后处理器(使用静态密钥)
  • 我已经试过了,它可以帮助@fatrixienicolie
  • 通过 github 分享您的代码库以获得更快的解决方案
  • @Nico Van Belle 谢谢!

标签: java spring spring-boot


【解决方案1】:

我建议在您的项目中搜索返回 PropertySourcesPlaceholderConfigurer 的 Bean。该对象可以配置为设置不同的前缀而不是“${”。这样做会导致您所描述的行为。

例如,创建此类我能够重现您的问题。

import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

public class PrefixConfiguration {

    @Bean
    public static PropertySourcesPlaceholderConfigurer configure(){
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer
                = new PropertySourcesPlaceholderConfigurer();
        propertySourcesPlaceholderConfigurer.setPlaceholderPrefix("%{");
        propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
        return propertySourcesPlaceholderConfigurer;
    }
}

您的 Bean 可能有所不同,它的存在可能是有充分理由的,所以不要在没有进一步调查的情况下盲目地删除它。

【讨论】:

  • 谢谢@gere,我根本没有看到 PropertySourcesPlaceholderConfigurer,我在升级第三方依赖项后遇到了这个问题。一旦我添加了 PropertySourcesPlaceholderConfigurer,它似乎工作正常
  • 然后PropertySourcesPlaceholderConfigurer 在第三方库中以改变正常行为的方式进行配置。当你自己添加它时,你是在再次声明它,并且这样做,让它再次正常工作。
  • 嘿为什么这-> static PropertySourcesPlaceholderConfigurer configure() 是一个静态方法?你能帮我理解吗?
  • 因为 Spring 文档建议这样做:在此处查找“BeanFactoryPostProcessor-returning @Bean methods”段落:docs.spring.io/spring-framework/docs/current/javadoc-api/org/… 它解释了原因,并使用了一个准确返回 PropertySourcesPlaceholderConfigurer 的 bean 作为示例。
猜你喜欢
  • 1970-01-01
  • 2018-03-18
  • 2021-09-15
  • 1970-01-01
  • 2020-02-02
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 2022-12-16
相关资源
最近更新 更多