我正在尝试使用 Spring 框架构建控制台应用程序。
我有一个由@SpringBootApplication
注释的类:
@SpringBootApplication
public class LoaderApplication {
public static void main(String[] args) {
SpringApplication.run(LoaderApplication.class, args);
}
}
以及被@Component
注解的类
@Component
public class ElasticLoader implements CommandLineRunner {
// Elastic properties
@Value("${elasticTransportAddress:#{null}}")
private String elasticTransportAddress;
private static final Logger log = LoggerFactory.getLogger(ElasticLoader.class);
@Override
public void run(String... arg) throws Exception {
if (!( elasticTransportAddress != null && elasticTransportAddress.isEmpty() )) {
log.error("[elasticTransportAddress] is not defined in property file");
return;
}
log.info("-> ElasticLoader.run");
}
}
如您所见,在这个类中,我尝试通过 @Value
注释注入(inject)属性 elasticTransportAddress
值,但是在运行我的应用程序后,我可以看到该属性 elasticTransportAddress
保持未分配状态。
我错过了什么?
让我添加一些注释:
我想将我的应用程序与不同的属性文件一起使用。对于这种情况,我创建了包含以下内容的 xml-context-config.xml
:
<beans profile="companies">
<!-- allows for ${} replacement in the spring xml configuration from the
application-default.properties, application-dev files on the classpath -->
<context:property-placeholder
location="classpath:companies.properties"
ignore-unresolvable="true" />
<!-- scans for annotated classes in the com.env.dev package -->
<context:component-scan base-package="ru.alexeyzhulin" />
</beans>
并使用我放在
中的配置文件companies.properties
我的运行配置与描述的配置文件:
并且此配置文件已启用,正如我在应用程序日志中看到的那样:
2017-01-15 00:10:39.697 INFO 10120 --- [ main] ru.alexeyzhulin.LoaderApplication : The following profiles are active: companies
但是当我在 application.properties
中定义属性并使用默认配置文件时,属性 elasticTransportAddress
被分配。
最佳答案
将 companies.properties 重命名为 application-companies.properties。 Link到文档
关于java - Spring 和@Value 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41653357/