JEE Study|JAVA EE|企业级开发学习网

标题: Spring Boot 读取 properties 文件属性 [打印本页]

作者: JeeStudy    时间: 2017-7-6 16:12
标题: Spring Boot 读取 properties 文件属性
Spring Boot 一贯秉承 默认配置,尽量让开发者尽量不配置或少配置。(为什么这么简单呢?
方法1:

用注解@Value读取配置文件的属性内容


        @Value("${website.author}")
        private String websiteAuthor;
        @Value("${website.name}")
        private String websiteName;

[Java] 纯文本查看 复制代码
        @Value("${website.author}")
        private String websiteAuthor;
        @Value("${website.name}")
        private String websiteName;



方法2:使用 @ConfigurationProperties 基于类型安全的properties配置
[Java] 纯文本查看 复制代码
/**
* @Auth:Angel
* @Date:2017年7月6日下午4:08:40
* @WebSite:www.jeestudy.com
*/
package com.jeestudy.hct;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
* @Title:WebSite.java
* @Auth:Angel
* @Date:2017-07-06 16:08:40
* @WebSite:www.jeestudy.com
* @Email:chengtai_he@163.com
* @Description:
*/
@ConfigurationProperties(prefix = "website")
public class WebSite {
        private String author;
        private String name;

        public String getAuthor() {
                return author;
        }

        public void setAuthor(String author) {
                this.author = author;
        }

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

}

[Bash shell] 纯文本查看 复制代码
application.properties

server.port=9090
server.CONTEXT_PATH=/hellospringboot

website.author=Angel
website.name=www.jeestudy.com

logging.file=D:/SpringBootLog.log
logging.level.org.springframework.web: DEBUG













作者: angel    时间: 2017-7-6 21:32
不错,这样绑定真省事




欢迎光临 JEE Study|JAVA EE|企业级开发学习网 (http://www.jeestudy.com/) Powered by Discuz! X3.2