正如标题,我的自定义属性:
#app settings
my.chassisNum=10
java代码:
@PropertySource("classpath:appconf.properties")
@ConfigurationProperties(prefix = "my" )
@Component
public class AppConfig {
private String chassisNum;
public String getChassisNum() {
return this.chassisNum;
}
public void setChassisNum(String chassisNum) {
this.chassisNum = chassisNum;
}
}
当 Spring Boot 启动完成时,我得到的“chassisNum”值为 10。
当我在其他地方得到它时,当 spring-boot 未启动完成时,它得到“null”
@Component
public class CreateBaseFolder {
private final Logger logger = LogManager.getLogger(CreateBaseFolder.class);
private File f;
@Autowired
AppConfig appconf;
public CreateBaseFolder() {
System.out.println(appconf.getChassisNum());
}
我尝试了很多方法来获取它的值,但都是错误的。例如:implements InitializingBean,@DependsOn ....
假设你有application.properties
内容:
foo.bar=Jerry
您将使用注释@Value
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GetPropertiesBean {
private final String foo;
@Autowired
public GetPropertiesBean(@Value("${foo.bar}") String foo) {
this.foo = foo;
System.out.println(foo);
}
}
当然,我们需要一个切入点
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后将类应用程序作为 Spring Boot 应用程序运行,组件自动加载,您将在控制台屏幕上看到结果
Jerry
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)