我有几个@Configuration
类,它们确实指定了自定义@ConfigurationProperties("sample")
,并且用于实例化稍后将在我的业务逻辑类中使用的多个bean。
但是,我一直在尝试使用内部@Component
类来执行此方法,因此无需将其适合于现有的特定或通用配置中,看看会发生什么。
@Component
@ConfigurationProperties("myclass")
public class MyClass {
private String attribute;
(Constructor, getters and setters for attribute and other methods...)
}
在我的application.properties
文件中,我确实将该属性值指定为myclass.attribute=value
。
以这种方式进行操作每次都会导致一个空值。 @Component
是否接受读取.properties文件,还是应该将其保存在@Configuration
类中?
答案 0 :(得分:0)
即使在带有@ConfigurationProperties
注释的类中使用@Component
,一切都按预期进行。请尝试:
application.properties:
myclass.attribute=value
MyClass类:
@Data
@Component
@ConfigurationProperties("myclass")
public class MyClass {
private String attribute;
}
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class FooTests {
@Autowired
private MyClass myClass;
@Test
public void test() {
System.out.println(myClass.getAttribute());
}
}
答案 1 :(得分:0)
您确实需要在配置类(例如应用程序类)上使用@EnableConfigurationProperties
注释。
@SpringBootApplication
@EnableConfigurationProperties
public class MySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApp.class);
}
}
答案 2 :(得分:0)
我从未使用过@ConfigurationProperties
批注,但是如果您想通过application.properties
中的值设置属性,我建议您使用@Value
批注:
application.properties:
myclass.attribute=foo
@Component
public class MyClass {
@Value("myclass.attribute")
private String attribute;
// ...
}
这样,MyClass
的每个实例都将具有attribute
,其默认值为foo
答案 3 :(得分:0)
我应该把它当作评论。但是不想让某人错过这个琐碎的事情。
好的,问题是-您缺少“ $”(美元符号)。想知道为什么没人注意到它吗?
在属性文件中(如果有):
myclass.attribute=value
然后在任何类中访问它,请执行以下操作:
@Value("${myclass.attribute}")
在上方加上$符号?