假设我定义了application.yml
:
spring:
profiles.active: development
---
spring:
profiles: development
logging:
level:
org.springframework.web: DEBUG
org.hibernate: ERROR
storage:
RemoteStorage:
name: "Server 1"
user: "test"
passwd: "test"
host: "163.218.233.106"
LocalStorage:
name: "Server 2"
user: "test2"
passwd: "test2"
host: "10.10.0.133"
---
storage
是一个自定义属性,我希望它像这样加载:
@Value("${storage}")
private List<Storage> AvailableStorage = new ArrayList<>();
道歉我是Spring框架的初学者。我试图做的是让RestController
根据请求提供的参数读取相应的配置,即?storage=RemoteStorage
之类的请求将使用RemoteStorage
配置。
答案 0 :(得分:2)
@Value注释不会加载列表或地图类型的属性。为此,您必须使用@ConfigurationProperties注释定义一个类,如下所示。
import java.util.List;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix ="storage")
public class MyProps {
private List<String> listProp;
private Map<String, String> mapProp;
public List<String> getListProp() {
return listProp;
}
public void setListProp(List<String> listProp) {
this.listProp = listProp;
}
public Map<String, String> getMapProp() {
return mapProp;
}
public void setMapProp(Map<String, String> mapProp) {
this.mapProp = mapProp;
}
}
以下是上述属性配置类的application.yaml文件。
storage:
listProp:
- listValue1
- listValue2
mapProp:
key1: mapValue1
key2: mapValue2
如果您使用的是application.properties文件而不是.yaml文件,那么
storage.listProp[0]=listValue1
storage.listProp[1]=listValue2
storage.mapProp.key1=mapValue1
storage.mapProp.key2=mapValue2