[英]Spring Boot - Cannot read application.yml values from instantiated object
我正在尝试使用 @ConfigurationProperties 注释从 application.yml 读取一些设置值。
TestClass
类的实例化对象使用了属性类,所以我添加了@Configurable
注解,但properties
始终为null
,导致 NullpointerException。
属性类:
@ConfigurationProperties
@Getter
@Setter
public class Properties {
private String setting;
}
以及使用属性的对象:
@Configurable
public class TestClass{
@Autowired
private Properties properties;
void print(){
System.out.println(properties.getSetting());
}
}
如果我调用 print 方法,会发生NullPointerException
:
TestClass testClass = new TestClass();
testClass.print();
我错过了什么吗?
简短的回答:
找到使用@SpringBootApplication
注释的类,并在其中添加注释@EnableConfigurationProperties(Properties.class)
@SpringBootApplication
@EnableConfigurationProperties(Properties.class)
public class ServiceLauncher {
解释:
@ConfigurationProperties
不会将带此注解的类注册为 spring bean。 它仅用于 Spring 可以读取带有一些元配置信息的属性(例如prefix = "some.prop.prefix"
)。
如果您希望将此类用作 spring bean(例如通过@Autowired
),您需要将上述注释与@EnableConfigurationProperties
结合起来,然后告诉 spring 这个类必须成为一个 spring bean。
另一种解决方法:
您也可以只在 Properties 类上使用@Component
,这样就足够了,不需要@EnableConfigurationProperties
但后者是更好的做法。
@Component
@ConfigurationProperties
@Getter
@Setter
public class Properties {
编辑:在评论中澄清后,此代码中还有另一个错误。 您应该将@Configurable
替换为@Configuration
。 第一个不在放置的类上创建spring bean!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.