spring - 在 Spring Boot 应用程序中加载 application.yml 的最佳方法
问题描述
我有 Spring Boot 应用程序和具有不同属性的 application.yml 并加载如下。
@Configuration
@ConfigurationProperties(prefix="applicationprops")
public class ApplicationPropHolder {
private Map<String,String> mapProperty;
private List<String> myListProperty;
//Getters & Setters
}
我的服务或控制器类,我在其中获得如下属性。
@Service
public ApplicationServiceImpl {
@Autowired
private ApplicationPropHolder applicationPropHolder;
public String getExtServiceInfo(){
Map<String,String> mapProperty = applicationPropHolder.getMapProperty();
String userName = mapProperty.get("user.name");
List<String> listProp = applicationPropHolder.getMyListProperty();
}
}
我的应用程序.yml
spring:
profile: dev
applicationprops:
mapProperty:
user.name: devUser
myListProperty:
- DevTestData
---
spring:
profile: stagging
applicationprops:
mapProperty:
user.name: stageUser
myListProperty:
- StageTestData
我的问题是
- 在我的服务类中,我正在定义一个变量并为每个方法调用分配 Propertymap。它是正确的方法吗?
- 有没有其他更好的方法可以在不分配局部变量的情况下获取这些地图。
解决方案
您可以通过三种简单的方法将值分配给 bean 类中的实例变量。
使用
@Value
注解如下@Value("${applicationprops.mapProperty.user\.name}") private String userName;
使用
@PostConstruct
注解如下@PostConstruct public void fetchPropertiesAndAssignToInstanceVariables() { Map<String, String> mapProperties = applicationPropHolder.getMapProperty(); this.userName = mapProperties.get( "user.name" ); }
在 setter 上使用
@Autowired
如下@Autowired public void setApplicationPropHolder(ApplicationPropHolder propHolder) { this.userName = propHolder.getMapProperty().get( "user.name" ); }
可能还有其他方法,但我想说这些是最常见的方法。
推荐阅读
- c - 将存储在 uint32_t 中的内存转换为 C 中的浮点数
- css - Flexbox 在打印视图中不分页(以及其他问题)
- java - 为什么我的 Printwriter 不能像我想要的那样工作?
- javascript - 如何从函数中提取参数而不将其更改为字符串?
- javascript - 反应单击项目以显示详细信息
- javascript - 反应全局函数
- django - Django:验证 GET 请求
- php - 如何以下面给出的形式访问上传的文件,我收到未定义的索引错误
- javascript - 如何对 iframe 内容使用相同的 javascript/jquery
- java - 为什么列表大小返回 0?