---
title: "Spring Boot使用自定义的properties"
author: "xiaowei2002"
date: "2015-07-31T15:18:49Z"
tags: []
categories: ["企业架构"]
slug: "spring-boot-properties"
draft: false
lastmod: "2015-08-20T15:50:21Z"
id: 2231918
url: "https://xiaowei2002.iteye.com/blog/2231918"
---

### [Spring Boot使用自定义的properties](http://wiselyman.iteye.com/blog/2184586)

**博客分类：**

- [spring-boot](http://wiselyman.iteye.com/category/325448)

 

 

      spring boot使用application.properties默认了很多配置。但需要自己添加一些配置的时候，我们应该怎么做呢。

 

# 若继续在application.properties中添加

如：

 

Properties代码     [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

1. wisely2.name=wyf2
2. wisely2.gender=male2

 

# 定义配置类：

Java代码     [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

01. @ConfigurationProperties(prefix = "wisely2")
02. public class Wisely2Settings {
03. private String name;
04. private String gender;
05. public String getName() {
06. return name;
07. }
08. public void setName(String name) {
09. this.name = name;
10. }
11. public String getGender() {
12. return gender;
13. }
14. public void setGender(String gender) {
15. this.gender = gender;
16. }
17. }

 

# 若新用新的配置文件

如我新建一个wisely.properties

Properties代码     [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

1. wisely.name=wangyunfei
2. wisely.gender=male

# 需定义如下配置类

 

Java代码     [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

01. @ConfigurationProperties(prefix = "wisely",locations = "classpath:config/wisely.properties")
02. public class WiselySettings {
03. private String name;
04. private String gender;
05. public String getName() {
06. return name;
07. }
08. public void setName(String name) {
09. this.name = name;
10. }
11. public String getGender() {
12. return gender;
13. }
14. public void setGender(String gender) {
15. this.gender = gender;
16. }
17. }

 

 

# 最后注意在spring Boot入口类加上@EnableConfigurationProperties

Java代码     [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

1. @SpringBootApplication
2. @EnableConfigurationProperties({WiselySettings.class,Wisely2Settings.class})
3. public class DemoApplication {
4. public static void main(String\[] args) {
5. SpringApplication.run(DemoApplication.class, args);
6. }
7. }

# 使用定义的properties

在别的bean中可直接注入

Java代码     [![收藏代码](http://wiselyman.iteye.com/images/icon_star.png)]()

01. @Controller
02. public class TestController {
03. @Autowired
04. WiselySettings wiselySettings;
05. @Autowired
06. Wisely2Settings wisely2Settings;
07. @RequestMapping("/test")
08. public @ResponseBody String test(){
09. System.out.println(wiselySettings.getGender()+"---"+wiselySettings.getName());
10. System.out.println(wisely2Settings.getGender()+"==="+wisely2Settings.getGender());
11. return "ok";
12. }
13. }

注意：也可以去掉

@EnableConfigurationProperties({PropSettings.class})  在属于类中加入