@Value在Spring @Configuration中不起作用

Ash*_*tra 5 java spring dependency-injection properties

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

我有一个配置类正在加载属性

WebConfig.java

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

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
       return new PropertySourcesPlaceholderConfigurer();
    }
}
Run Code Online (Sandbox Code Playgroud)

我有另一个配置类,我试图在其中使用这些属性

MyServerConfig.java

@Configuration
class MyServerConfig {

    @Value("${server.url}")
    private String url;
...
}
Run Code Online (Sandbox Code Playgroud)

application.properties

server.url=http://localhost:8080/test/abc
Run Code Online (Sandbox Code Playgroud)

但是得到:

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

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

Nik*_*las 0

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

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

    @Value( "${server.url}" )
    private String url;
}
Run Code Online (Sandbox Code Playgroud)