Spring-boot 允许我们提供多种方式来提供外部化配置,你可以尝试使用 application.yml 或 yaml 文件代替属性文件,并根据不同的环境提供不同的属性文件设置。
我们可以将每个环境的属性分离到单独的spring配置文件下的单独的yml文件中。然后在部署期间您可以使用:
java -jar -Drun.profiles=SpringProfileName
指定要使用的弹簧配置文件。注意yml文件的名称应类似于
application-{environmentName}.yml
让它们被 springboot 自动占用。
参考:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties
从 application.yml 或属性文件中读取:
从属性文件或yml中读取值的最简单方法是使用spring的@value注解。Spring会自动将yml中的所有值加载到spring环境中,所以我们可以直接使用来自环境的那些值,例如:
@Component
public class MySampleBean {
@Value("${name}")
private String sampleName;
// ...
}
或者spring提供的另一种读取强类型bean的方法如下:
YML
ymca:
remote-address: 192.168.1.1
security:
username: admin
对应POJO读取yml:
@ConfigurationProperties("ymca")
public class YmcaProperties {
private InetAddress remoteAddress;
private final Security security = new Security();
public boolean isEnabled() { ... }
public void setEnabled(boolean enabled) { ... }
public InetAddress getRemoteAddress() { ... }
public void setRemoteAddress(InetAddress remoteAddress) { ... }
public Security getSecurity() { ... }
public static class Security {
private String username;
private String password;
public String getUsername() { ... }
public void setUsername(String username) { ... }
public String getPassword() { ... }
public void setPassword(String password) { ... }
}
}
上述方法适用于 yml 文件。
参考:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html