讀取application.yml下配置參數信息
在application.yml
文件內容
my: remote-address: 192.168.1.1 yarn: weburl: http://192.168.1.1:8088/ws/v1/cluster/ security: username: foo roles: - USER - ADMIN
創建FooProperties.java
文件,並使用@ConfigurationProperties
注解
@Component @ConfigurationProperties(prefix = "my") public class MyPorperties { private final Yarn yarn = new Yarn(); private InetAddress remoteAddress; private final Security security = new Security(); public InetAddress getRemoteAddress() { return remoteAddress; } public void setRemoteAddress(InetAddress remoteAddress) { this.remoteAddress = remoteAddress; } public Security getSecurity() { return security; } public Yarn getYarn() { return yarn; } public static class Security { private String userName; private List<String> roles = new ArrayList<>(Collections.singleton("USER")); public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } @Override public String toString() { return "Security{" + "userName='" + userName + '\'' + ", roles=" + roles + '}'; } } public static class Yarn { private String webUrl; public String getWebUrl() { return webUrl; } public void setWebUrl(String webUrl) { this.webUrl = webUrl; } @Override public String toString() { return "Yarn [webUrl=" + webUrl + "]"; } } }
調用
@RestController public class TestController { @Autowired private MyPorperties my; @RequestMapping("/myProperties") public Map<String, Object> getFooProperties() { Map<String, Object> map = new HashMap<>(); map.put("remote-address", my.getRemoteAddress()); map.put("security", my.getSecurity().toString()); map.put("yarn", my.getYarn().toString()); return map; } }
測試
訪問:http://localhost:8080/myProperties
參考《https://blog.csdn.net/u013887008/article/details/79368173》
java -jar啟動時項目修改參數
項目已經發布,在啟動時可以通過傳遞參數修改啟動參數:
java -jar \
-Dspring.profiles.active=prod \
-Dserver.port=8080 \
my-web-1.0.0-SNAPSHOT.jar
或者可以吧整個application.yml文件放在jar外邊,啟動時指定文件路徑:
java -jar demo.jar --Dspring.config.location=路徑(application.yml)