正如标题所述,我的自定义属性在应用程序启动时没有注册。你介意看一下吗?
我的custom.yml
bridge:
url: xxx
authentication:
auth-url: xxx
user: xxx我的BridgeProperties.java
@Component
@PropertySource("classpath:custom.yml")
@ConfigurationProperties(
prefix = "bridge"
)
public class BridgeProperties {
@NestedConfigurationProperty
protected ApiProperties apiProperties = new ApiProperties();
}我的ApiProperties.java
public class ApiProperties {
protected String url;
protected ApiProperties.Authentication authentication;
// getter and setter
public ApiProperties() {
}
public static class Authentication {
protected String authUrl;
protected String user;
public Authentication() {}
// getter and setter
}我的申请的入口点:
@SpringBootApplication
@PropertySources(value = {
@PropertySource("classpath:application.yml"),
@PropertySource("classpath:custom.yml")
})
public class IntegrationService {
public static void main(String... args) {
SpringApplication.run(IntegrationService.class, args);
}
}当打印到命令行时,我得到null,而不是分配给custom.yml中的url、auth-url和user的值。
发布于 2022-06-27 23:11:45
正如白龙遗址中提到的
还值得一提的是,YAML文件不支持@PropertySource注释,因此如果我们需要使用该注释,它将限制我们使用属性文件。
如果确实需要以yaml格式导入其他外部文件,则必须实现自己的PropertySourceFactory,就像在这篇文章中一样。
对我来说,我看不到不使用默认application.yml的好处,因为您可以定义由不同Properties类管理的多个节。
例如,如果您只是将属性放在application.yml中,并且使用最近的JDK (>=jdk 14)进行编译,甚至可以使用该记录以非常紧凑的方式管理您的属性:
您所要做的只是添加EnableConfigurationProperties注释:
@SpringBootApplication
@EnableConfigurationProperties(BridgeProperties.class)
public class IntegrationService {
public static void main(String... args) {
SpringApplication.run(IntegrationService.class, args);
}
}并定义用于映射yaml属性的记录:
@ConfigurationProperties(prefix = "bridge")
public final record BridgeProperties(String url, Authentication authentication) {
public record Authentication(String authUrl, String user){
}
}记住,如果使用profile dev启动应用程序,也可以在配置文件(如application-dev.yml )中定义环境变量,例如,如果生产概要文件名为prd,则为生产application-prd.yml定义环境变量。您仍然可以将公共属性保留在application.yml中。
如果您真的想进入外部文件路径,我建议切换到.properties,因为@PropertySource本机支持它。
https://stackoverflow.com/questions/71067273
复制相似问题