【问题标题】:@Value not working in Spring @Configuration@Value 在 Spring @Configuration 中不起作用
【发布时间】:2017-10-04 12:33:50
【问题描述】:

需要帮助,问题出在哪里?

我有一个将属性加载为的配置类

WebConfig.java

@Configuration
@PropertySource(value={"classpath:application.properties"})
class WebConfig extends WebMvcConfigurerAdapter{

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

我有另一个配置类,我正在尝试将属性用作

MyServerConfig.java

@Configuration
class MyServerConfig {

    @Value("${server.url}")
    private String url;
...
}

application.properties

server.url=http://localhost:8080/test/abc

但是得到:

java.lang.IllegalArgumentException:无法解析占位符“server.url”。

不知道这里缺少什么?有什么想法吗?

【问题讨论】:

  • 你为什么在WebConfigstatic类中创建方法propertySourcesPlaceholderConfigurer
  • 你能发布你的配置 application.properties 文件吗?
  • @Jesper 只是尝试我在谷歌找到的解决方案之一,即使您删除静态或完全删除该方法也无法正常工作
  • @SamDev 已经在问题中了,再检查一遍

标签: java spring dependency-injection properties


【解决方案1】:

在将使用某个属性的类中使用@PropertyScan注解:

@Configuration
@PropertyScan("classpath:application.properties")
class MyServerConfig {

    @Value( "${server.url}" )
    private String url;
}

【讨论】:

  • 有什么错误吗? “不适合我”也无法帮助我找到适合您的解决方案。
  • 它在这里不起作用,而在@Service类中以类似的方式工作
  • 与问题中提到的错误相同。 java.lang.IllegalArgumentException:无法解析占位符“server.url”
  • 我认为您的意思是@ComponentScan@PropertySource,因为没有名为@PropertyScan 的注释
【解决方案2】:

为了获取@Value 变量的值,不需要以任何特殊方式配置application.properties,因为始终会扫描此文件。所以去掉@PropertySource注解和PropertySourcesPlaceholderConfigurer bean。

如果您想添加其他 .properties 文件(例如 constants.propertiesdb-config.properties),则使用这些。

所以只需删除这些并尝试再次运行您的应用程序

非常重要:

  1. 确保扫描使用 @Value 注释的类(如果您的 BootApplication 位于某个包而不是“主”包中,请添加正确的 @SpringBootApplication(scanBasePackages = { "com.my.project" }) 注释)。

  2. 确保您的 application.properties 在您的类路径中。

奖励如果您使用的是弹簧配置文件(例如:proddev),您还可以拥有 application-prod.propertiesapplication-dev.properties 文件,这些文件将被扫描并包含在内,具体取决于哪个文件您正在运行的配置文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 2018-03-03
    • 2017-10-10
    • 1970-01-01
    相关资源
    最近更新 更多