在我的项目中,需要检索映射中的属性文件值。这就是我编写代码以检索映射中的属性文件值的方式。但是值在地图中不具有约束力。我该如何实现?我想念什么吗?
specialist.properties
@Configuration
@ConfigurationProperties(prefix = "specialist")
@PropertySource("classpath:specialist.properties")
public class SpecialistProperties {
private Map<String,String> specialist=new HashMap<String,String>();
public Map<String, String> getSpecialist() {
return specialist;
}
public void setSpecialist(Map<String, String> specialist) {
this.specialist = specialist;
}
}
控制器类:
@RestController
public class MyappController {
@Autowired
private SpecialistProperties specialistProperties;
@GetMapping(value="/specialist")
public Map<String,String> getSpecialist()
{
return specialistProperties.getMap();
}
}
specialist.properties
specialist.name=Sam
specialist.availableDay=Wednesday
specialist.availableTime=5PM
答案 0 :(得分:0)
您可以如下所示设置属性。
使用以下代码创建名称为 application.properties 的文件:
example.hello=Hello
example.user=Abhimanyu
example.howru=How are you?
example.mapProperty.key1=MapValue1
example.mapProperty.key2=MapValue2
example.listProperty[0]=ListValue1
example.listProperty[1]=ListValue2
OR:
使用以下代码创建名称为 application.yml 的文件
example:
hello: Hello
user: Abhimanyu
howru: How are you?
mapProperty:
key1: MapValue1
key2: MapValue2
listProperty:
ListValue1
ListValue2
您可以通过访问https://jsonformatter.org/yaml-validator
在线验证/格式化yaml文件供参考,请点击以下链接:http://jcombat.com/spring/how-to-read-properties-using-spring-boot-configurationproperties
答案 1 :(得分:0)
我通过添加 @ConfigurationProperties(prefix =“ specialist”)犯了一个错误。不需要 prefix =“ specialist” 。因为我已将地图属性值添加为 specialist ,所以在ConfigurationProperties前缀中不需要专家。更改之后,效果很好。
@Configuration
@ConfigurationProperties
@PropertySource("classpath:specialist.properties")
public class SpecialistProperties {
private Map<String,String> prop=new HashMap<String,String>();
public Map<String, String> getProp() {
return prop;
}
public void setProp(Map<String, String> prop) {
this.prop = prop;
}
}