在spring启动应用程序中加载application.yml的最佳方法

时间:2018-06-01 23:07:53

标签: spring spring-boot

我正在使用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();

}
}

我的application.yml

spring:
    profile: dev
applicationprops:
  mapProperty:
    user.name: devUser
  myListProperty:
        - DevTestData
---
spring:
    profile: stagging
applicationprops:
  mapProperty:
    user.name: stageUser
  myListProperty:
        - StageTestData

我的问题是

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

2 个答案:

答案 0 :(得分:2)

有三种简单的方法可以将值分配给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. 在设置器上使用@Autowired,如下所示

    @Autowired
    public void setApplicationPropHolder(ApplicationPropHolder propHolder) {
      this.userName = propHolder.getMapProperty().get( "user.name" );
    }
    
  4. 可能还有其他人,但我认为这些是最常见的方式。

答案 1 :(得分:1)

希望你的代码很好。

只需使用以下

即可
@Configuration
@ConfigurationProperties(prefix="applicationprops")
public class ApplicationPropHolder {

private Map<String,String> mapProperty;
private List<String> myListProperty;

public String getUserName(){
    return mapProperty.get("user.name");
}

public String getUserName(final String key){
    return mapProperty.get(key);
}

}

@Service
public ApplicationServiceImpl {

@Autowired
private ApplicationPropHolder applicationPropHolder;

public String getExtServiceInfo(){

final String userName = applicationPropHolder.getUserName();

final List<String> listProp = applicationPropHolder.getMyListProperty();

}
}
相关问题