SpringBoot(十):读取application.yml下配置参数信息,java -jar启动时项目修改参数

读取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)

 

posted @ 2019-01-28 17:06  cctext  阅读(14919)  评论(0编辑  收藏  举报