根据Spring in action fifth edition的第5章,我尝试使用spring boot建立自己的配置变量:
@Component
@ConfigurationProperties(prefix = "myprops")
public class MyClass {
private int myvar1;
// Getters and setters...
}
仅在以下情况下写在文件application.properties
中:
myprops.myvar1=3333
MyClass.getMyvar1()
现在应该返回3333
,但仍返回默认的int值:0
。
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
@Bean
public CommandLineRunner foo(ApplicationContext ctx) {
return args -> {
MyClass mc = new MyClass();
int x = mc.getMyvar1();
System.out.println(x);
};
}
}
答案 0 :(得分:0)
将@EnableConfigurationProperties(MyClass.class)添加到Demo1Application
如果我们不在POJO中使用@Configuration,则需要在主Spring应用程序类中添加@EnableConfigurationProperties(ConfigProperties.class),以将属性绑定到POJO: