示例如下:
1. 新建 Maven 项目 properties
2. pom.xml
4.0.0 com.java properties 1.0.0 org.springframework.boot spring-boot-starter-parent 2.0.5.RELEASE org.springframework.boot spring-boot-starter-web org.projectlombok lombok provided org.springframework springloaded 1.2.8.RELEASE provided org.springframework.boot spring-boot-devtools provided ${project.artifactId} org.apache.maven.plugins maven-compiler-plugin org.springframework.boot spring-boot-maven-plugin repackage
3. 配置文件 user-defined.properties
aaa.url.login=aaa-login.htmlaaa.url.order=aaa-order.htmlbbb.goods.price=500bbb.goods.weight=1000
4. PropertiesStarter.java
package com.java;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * 主启动类 * * @author Storm * */@SpringBootApplicationpublic class PropertiesStarter { public static void main(String[] args) { SpringApplication.run(PropertiesStarter.class, args); }}
5. URLProperties.java
package com.java.properties;import org.springframework.boot.context.properties.ConfigurationProperties;import lombok.Data;/** * 前缀为aaa.url的配置自动注入到对应属性中 * * @author Storm * */@Data@ConfigurationProperties(prefix = "aaa.url")public class URLProperties { private String login; private String order;}
6. GoodsProperties.java
package com.java.properties;import org.springframework.boot.context.properties.ConfigurationProperties;import lombok.Data;/** * 前缀为bbb.goods的配置自动注入到对应属性中 * * @author Storm * */@Data@ConfigurationProperties(prefix = "bbb.goods")public class GoodsProperties { private String price; private String weight;}
7. PropertiesConfig.java
package com.java.config;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import com.java.properties.GoodsProperties;import com.java.properties.URLProperties;/** * 用户自定义配置文件配置类 * * @author Storm * */@Configuration@PropertySource({ "classpath:user-defined.properties" })@EnableConfigurationProperties({ URLProperties.class, GoodsProperties.class })public class PropertiesConfig {}
8. DemoController.java
package com.java.controller;import java.util.HashMap;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import com.java.properties.GoodsProperties;import com.java.properties.URLProperties;@RestControllerpublic class DemoController { @Autowired private URLProperties url; @Autowired private GoodsProperties goods; @GetMapping("/getProperties") public MapgetProperties() { System.out.println(url.getOrder()); Map map = new HashMap<>(); map.put("url", url); map.put("goods", goods); return map; }}
9. 运行 PropertiesStarter.java ,启动测试
浏览器输入
返回结果如下:
{"goods":{"price":"500","weight":"1000"},"url":{"login":"aaa-login.html","order":"aaa-order.html"}}
配置加载成功!
Spring boot 自动配置自定义配置文件
.