use*_*539 5 java spring yaml spring-mvc spring-boot
假设我有这个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"
---
Run Code Online (Sandbox Code Playgroud)
这storage是一个自定义属性,我希望它像这样加载:
@Value("${storage}")
private List<Storage> AvailableStorage = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)
抱歉,我是 Spring 框架的初学者。我试图做的是RestController根据请求提供的参数读取相应的配置,即类似的请求?storage=RemoteStorage将使用RemoteStorage配置。
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
下面是上述属性配置类的 application.yaml 文件。
storage:
listProp:
- listValue1
- listValue2
mapProp:
key1: mapValue1
key2: mapValue2
Run Code Online (Sandbox Code Playgroud)
如果您使用 application.properties 文件而不是 .yaml 文件,那么
storage.listProp[0]=listValue1
storage.listProp[1]=listValue2
storage.mapProp.key1=mapValue1
storage.mapProp.key2=mapValue2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6367 次 |
| 最近记录: |