Java 来自Yml文件的Spring启动和属性数据
我的Spring boot应用程序无法使用application.yml中的properties对象创建bean 以下是我所做的:Java 来自Yml文件的Spring启动和属性数据,java,spring-boot,Java,Spring Boot,我的Spring boot应用程序无法使用application.yml中的properties对象创建bean 以下是我所做的: application.yml: statsd: host: 10.0.5.23 port: 8125 我创建了一个StatsdProperties@Component类来保存上述数据: @Component @ConfigurationProperties(prefix="statsd") public class StatsdProperties
application.yml:
statsd:
host: 10.0.5.23
port: 8125
我创建了一个StatsdProperties@Component
类来保存上述数据:
@Component
@ConfigurationProperties(prefix="statsd")
public class StatsdProperties {
private String host;
private int port;
.... getters & setters
}
我创建了另一个@Component
类,该类应使用上述属性:
@Component
public class MyClass{
@Autowired
private StatsdProperties statsdProperties;
public MyClass(){
statsdProperties.getPort() <--- statsdProperties is null here
}
@组件
公共类MyClass{
@自动连线
私人国有资产国有资产;
公共MyClass(){
statsdProperties.getPort()您需要在MyClass
中启用配置:
@Component
@EnableConfigurationProperties(StatsdProperties.class)
public class MyClass
将配置文件更新为:
@Configuration
@EnableConfigurationProperties()
@ConfigurationProperties(prefix = "statsd")
public class StatsdProperties {
private String host;
private int port;
.... getters & setters
}
用@Value
注释字段,如@Value(${host}”)
看起来没有扫描StatsdProperties,实际上也没有创建Bean。请尝试使用@Bean模式执行相同操作。#shahaf在添加@值之后…
我遇到了以下错误:BeanCreationException:创建名为“StatsdProperties”的Bean时出错:自动连线依赖项的注入失败;嵌套异常为java.lang.IllegalArgumentException:无法解析值“${host}”中的占位符“host”
@riorio愚蠢的问题…您的类是否用@Configuration
注释?您可以使用@value
或@ConfigurationProperties
但无需同时执行这两个操作,除非您使用的字段名称与未更改空位置的配置不同。您的属性路径是什么?您可以将其共享给其他Spring p吗应用程序可以正确读取yml中的属性。例如spring:jpa:database:mysql尝试在MyClass
StatsdProperties中用@配置
替换@组件