首页 > 解决方案 > 在 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

我的问题是

  1. 在我的服务类中,我正在定义一个变量并为每个方法调用分配 Propertymap。它是正确的方法吗?
  2. 有没有其他更好的方法可以在不分配局部变量的情况下获取这些地图。

标签: springspring-boot

解决方案


您可以通过三种简单的方法将值分配给 bean 类中的实例变量。

  1. 使用@Value注解如下

    @Value("${applicationprops.mapProperty.user\.name}")
    private String userName;
    
  2. 使用@PostConstruct注解如下

    @PostConstruct
    public void fetchPropertiesAndAssignToInstanceVariables() {
      Map<String, String> mapProperties = applicationPropHolder.getMapProperty();
      this.userName = mapProperties.get( "user.name" );
    }
    
  3. 在 setter 上使用@Autowired如下

    @Autowired
    public void setApplicationPropHolder(ApplicationPropHolder propHolder) {
      this.userName = propHolder.getMapProperty().get( "user.name" );
    }
    

可能还有其他方法,但我想说这些是最常见的方法。


推荐阅读