spring @Value在有些情况下无法获取到值
原因1:多环境配置文件,检查mvn build的配置文件是否是当前环境
原因2:比如创建bean的时候,需要用到@Value的值,这时候@Value还未初始化
原因1的解决办法:
clean install -s xxx/setting.xml -Dmaven.test.skip=true -Denv=xxx
原因2的解决办法:
可以通过将属性写到@ConfigurationProperties注解类中去
@ConfigurationProperties("spring.elasticsearch")
public class ElasticsearchProperties {
/**
* Comma-separated list of the Elasticsearch instances to use.
*/
private List<String> uris = new ArrayList<>(Collections.singletonList("http://localhost:9200"));
}
例如:这种方式获取不到@Value的值,项目启动报错:Could not resolve placeholder 'spring.elasticsearch.uris' in value "${spring.elasticsearch.uris}"
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.xxx")
public class ElasticRestClientConfig extends AbstractElasticsearchConfiguration {
@Value("${spring.elasticsearch.uris}")
private List<String> url;
}
改成这种就可以
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.xxx")
public class ElasticRestClientConfig extends AbstractElasticsearchConfiguration {
@Autowired
private ElasticsearchProperties properties;
}