1.在resources下创建application-test.properties配置文件

2.在application-test.properties配置文件定义属性

test.port=8080
test.siteName=潇洒哥

3.pom. 中添加processor依赖

<!--  processor依赖开始-->
<dependency>
    <groupId>org.spring work.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
<!-- processor 依赖结束-->

不然实体类SpringBootReadProperties会报错

\"\"

4.创建配置管理的实体类SpringBootReadProperties

package com.study.model.entity;

import org.spring work.boot.context.properties.ConfigurationProperties;
import org.spring work.context.annotation.PropertySource;
import org.spring work.stereotype.Component;

@PropertySource(value = {\"classpath:application-test.properties\"})
@ConfigurationProperties(prefix = \"test\")
@Component
public class SpringBootReadProperties {
    private String port;
    private String sitename;
    public String getPort(){
        return port;
    }
    public void setPort(String port){
        this.port=port;
    }
    public String getSitename(){
        return sitename;
    }
    public void setSitename(String siteName){
        this.sitename=siteName;
    }
    @Override
    public String toString() {
        return \"SpringBootReadProperties{\" +
                \"port=\'\" + port + \'\\\'\' +
                \", siteName=\'\" + sitename + \'\\\'\' +
                \'}\';
    }
}
注意路径文件名:要全写

5.在controller包中创建测试ReadPropertiesController

package com.study.model.controller;

import com.study.model.entity.SpringBootReadProperties;
import org.spring work.beans.factory.annotation.Autowired;
import org.spring work.web.bind.annotation.RequestMapping;
import org.spring work.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = \"/read\")
public class ReadPropertiesController {
    @Autowired
    private SpringBootReadProperties readProperties;
    @RequestMapping(value = \"/read\")
    public String readProperties(){
        System.out.println(readProperties.toString());
        return readProperties.toString();
    }

}

6.访问http://localhost:8080/read/read就能得到相应的属性值


 

 

 

收藏 打印