首页 > 解决方案 > 春天。在类字段中加载完整的属性文件作为映射

问题描述

这应该很容易。但我不知道。磁盘上的文件“props.properties”。文件中的任何属性在哪里。我有一类配置:

@Configuration
@PropertySource(value = "file:props.properties", encoding = "utf8")
public class AppConfig {
...
  @Some_spring_annotation  <-- that is qestion
  private Map map;
...
}

如何通过 Spring 将所有属性从“props.properties”加载到“map”?

标签: springspring-bootproperties-file

解决方案


您可以将整个 porperties 文件加载为 Map,方法是将其定义为 PropertiesFactoryBean,然后将其与 @Resource 注释一起使用。

@Configuration
@PropertySource(value = "file:src/main/resources/test.properties", encoding = "utf8")
public class AppConfig {

@Value("${propertyname}")
String prop;

@Resource(name = "propertyBean")
private Map<String, String> propMap;

@Bean(name = "propertyBean")
public static PropertiesFactoryBean mapper() {
        PropertiesFactoryBean bean = new PropertiesFactoryBean();
        bean.setLocation(new FileSystemResource("src/main/resources/test.properties"));
        return bean;
}

public Map<String, String> getPropMap() {
    return propMap;
}
}

并使用如下键访问属性文件中存在的任何键:-

@RestController
public class Test {

@Autowired
private AppConfig appConfig;

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String  login(HttpServletRequest request){
    return appConfig.getPropMap().get("application.name");
}

}



test.propeties:-
server.port1=8099
application.name=edge-service
propertyname=dddd

在这种情况下,您不需要每次都编写@Value 注解,您可以使用 propMap 访问值。如果您想阅读单键使用

@Value("${propertyname}")
String prop;

即使您可以将地图数据定义到属性文件中

propertyname={key1:'value1',key2:'value2'}

根据需求,可以有很多实现来实现它。


推荐阅读