SpringBoot 學習記錄(八): properties 屬性自定義

這篇我們來學習如何在java bean 中使用我們自定義的屬性

一,引入依賴包

<!-- 支持自定義配置參數 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
	<optional>true</optional>
</dependency>
二,在application.properties中自定義屬性參數,這裏分幾種情況

1) 單個屬性參數

先在application.properties中定義幾個屬性:

com.demo.title=big.title
com.demo.description=test
com.demo.num=${random.int}  
com.demo.value=${random.value}
com.demo.msg=\u6D4B\u8BD5\u6807\u9898\uFF1A${com.demo.title}
這裏說明一下:

num:可以使用random生成隨機數,引用方法有

${random.int}

${random.long}

${random.int(10)} == 10以內的隨機數

${random.int[10,20]} == 10-20的隨機數

value:可以使用random生成隨機字符串(32位)

msg:可以引用文件內部定義的屬性值,引用方法${key}

新建java類DemoProperties,注入自定義的屬性值,這裏主要使用註解@Value

package com.example.properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component//交由spring管理
public class DemoProperties {
	
	/**
	 * 給定一個默認值,當讀取不到key值com.demo.title時啓用默認值
	 */
	@Value("${com.demo.title:default.title}")
	private String title;
	
	/**
	 * 沒有給定默認值,當讀取不到key值時會拋異常
	 */
	@Value("${com.demo.description}")
	private String description;
	
	/**
	 * 隨機數
	 */
	@Value("${com.demo.num}")
	private String num;
	
	/**
	 * 隨機字符串
	 */
	@Value("${com.demo.value}")
	private String value;
	
	/**
	 * 內部引用屬性
	 */
	@Value("${com.demo.msg}")
	private String msg;
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getNum() {
		return num;
	}
	public void setNum(String num) {
		this.num = num;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}

	
}
新建測試類ConfigController
package com.example.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.base.ReturnResult;
import com.example.constant.ReturnConstant;
import com.example.properties.ConfigProperties;
import com.example.properties.DemoProperties;

/**
 * 測試讀取自定義屬性
 * @author Administrator
 *
 */

@RestController
@RequestMapping("/properties")
public class ConfigController {

	@Resource
	private DemoProperties demoProperties;
		
	@RequestMapping("/demo")
	public ReturnResult getDemoProp(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("demo", demoProperties);
		ReturnResult r = new ReturnResult();
		r.setStatus(ReturnConstant.RETURN_OK);
		r.setMsg("自定義單個屬性");
		r.setResult(map);
		return r;
	}
	
}
訪問測試:http://localhost:8088/spring-boot/properties/demo

返回結果如下:

{
  "status": "true",
  "msg": "自定義單個屬性",
  "result": {
    "demo": {
      "title": "big.title",
      "description": "test",
      "num": "2050553421  ",
      "value": "09f706565ea9d4a961278578039e073f",
      "msg": "測試標題:big.title"
    }
  }
}
2) 多個屬性參數

先在application.properties中定義幾個屬性:

com.conf.group.name=group
com.conf.group.number=10
com.conf.group.system=\u4EBA\u5458\u7BA1\u7406
com.conf.group.local-path=127.0.0.1:8080
com.conf.group.user[0]=Lily
com.conf.group.user[1]=Sam
com.conf.group.user[2]=Jessie
這裏說明一下:

屬性local-path不符合java命名規範,注入時參數名可以用localPath來匹配

屬性user是定義的一個數組,注入時用list來接收參數

新建java類ConfigProperties,注入自定義的屬性值,這裏主要使用註解@ConfigurationProperties

package com.example.properties;

import java.util.List;

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

import com.example.entity.TestUser;

@Component//交由spring管理
//prefix設置key的前綴;
@ConfigurationProperties(prefix="com.conf.group")
public class ConfigProperties {

	/**
	 * 屬性後綴要對應配置文件中設置的key
	 * key值有-連接符的可以自動匹配爲java規範命名
	 * 定義的數組用集合封裝 
	 */
	
	private String name;
	
	private int number;
	
	private String system;
	
	private String localPath;
	
	private List<String> user;
	
	
	public String getName() {
		return name;
	}

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

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public String getSystem() {
		return system;
	}

	public void setSystem(String system) {
		this.system = system;
	}

	public String getLocalPath() {
		return localPath;
	}

	public void setLocalPath(String localPath) {
		this.localPath = localPath;
	}

	public List<String> getUser() {
		return user;
	}

	public void setUser(List<String> user) {
		this.user = user;
	}
	
}
在ConfigController中添加測試方法:
package com.example.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.base.ReturnResult;
import com.example.constant.ReturnConstant;
import com.example.properties.ConfigProperties;
import com.example.properties.DemoProperties;

/**
 * 測試讀取自定義屬性
 * @author Administrator
 *
 */

@RestController
@RequestMapping("/properties")
public class ConfigController {

	@Resource
	private DemoProperties demoProperties;
	
	@Resource
	private ConfigProperties configProperties;
	
	@RequestMapping("/demo")
	public ReturnResult getDemoProp(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("demo", demoProperties);
		ReturnResult r = new ReturnResult();
		r.setStatus(ReturnConstant.RETURN_OK);
		r.setMsg("自定義單個屬性");
		r.setResult(map);
		return r;
	}
	
	@RequestMapping("/conf")
	public ReturnResult getConfProp(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("conf", configProperties);
		ReturnResult r = new ReturnResult();
		r.setStatus(ReturnConstant.RETURN_OK);
		r.setMsg("自定義多個屬性");
		r.setResult(map);
		return r;
	}
}
啓動服務,訪問測試:http://localhost:8088/spring-boot/properties/conf

返回結果如下:

{
  "status": "true",
  "msg": "自定義多個屬性",
  "result": {
    "conf": {
      "name": "group",
      "number": 10,
      "system": "人員管理",
      "localPath": "127.0.0.1:8080",
      "user": [
        "Lily",
        "Sam",
        "Jessie"
      ]
    }
  }
}
三,除了在默認的application.properties中定義屬性,我們還可以自定義一個properties文件

config.properties

com.conf.group.name=group
com.conf.group.number=5
com.conf.group.system=\u4EBA\u5458\u7BA1\u7406
com.conf.group.local-path=127.0.0.1:8088
com.conf.group.user[0]=Lucy
com.conf.group.user[1]=Susan
com.conf.group.user[2]=Joly
這裏方便測試,屬性key值沒有變,只是改變了value值

那麼給java類ConfigProperties注入屬性值時如何指定配置文件呢?

很簡單,只需要在註解@ConfigurationProperties中添加一個屬性:locations="classpath:config.properties"

@Component//交由spring管理
//prefix設置key的前綴;
@ConfigurationProperties(prefix="com.conf.group",locations="classpath:config.properties")
public class ConfigProperties {
	
}
啓動測試,看是否讀取的是config.properties中的屬性值

http://localhost:8088/spring-boot/properties/conf

查看返回結果:

{
  "status": "true",
  "msg": "自定義properties文件,定義多個屬性",
  "result": {
    "conf": {
      "name": "group",
      "number": 5,
      "system": "人員管理",
      "localPath": "127.0.0.1:8088",
      "user": [
        "Lucy",
        "Susan",
        "Joly"
      ]
  }
}

可以看到,讀取到的屬性值確實已經改變了。

四,在配置文件中我們還可以定義一個對象的屬性值,首先在config.properties中添加如下屬性:
com.conf.group.testUser.name=user_name
com.conf.group.testUser.age=22
com.conf.group.testUser.gender=M
這裏的屬性值testUser將由一個自定義的對象來接收,

我們定義一個普通java類TestUser,在其中定義匹配的屬性名

package com.example.entity;

/**
 * 自定義屬性可以用實體類來接收
 * @author Administrator
 *
 */
public class TestUser {

	private String name;
	
	private int age;
	
	private String gender;

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}
	
	
}
在ConfigProperties中添加屬性:
        private TestUser testUser;

	public TestUser getTestUser() {
		return testUser;
	}

	public void setTestUser(TestUser testUser) {
		this.testUser = testUser;
	}
再來測試:http://localhost:8088/spring-boot/properties/conf

返回結果如下:

{
  "status": "true",
  "msg": "自定義properties文件,定義多個屬性",
  "result": {
    "conf": {
      "name": "group",
      "number": 5,
      "system": "人員管理",
      "localPath": "127.0.0.1:8088",
      "user": [
        "Lucy",
        "Susan",
        "Joly"
      ],
      "testUser": {
        "name": "user_name",
        "age": 22,
        "gender": "M"
      }
    }
  }
}
五,以上都是通過java類直接注入屬性值,下面我們來看如何在注入bean的時候注入自定義屬性

1) 刪除ConfigProperties的類註解,使其成爲一個普通java類

package com.example.properties;

import java.util.List;

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

import com.example.entity.TestUser;

//@Component//交由spring管理
//prefix設置key的前綴;
//@ConfigurationProperties(prefix="com.conf.group",locations="classpath:config.properties")
public class ConfigProperties {

	/**
	 * 屬性後綴要對應配置文件中設置的key
	 * key值有-連接符的可以自動匹配爲java規範命名
	 * 定義的數組用集合封裝 
	 */
	
	private String name;
	
	private int number;
	
	private String system;
	
	private String localPath;
	
	private List<String> user;
	
	private TestUser testUser;

	public String getName() {
		return name;
	}

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

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public String getSystem() {
		return system;
	}

	public void setSystem(String system) {
		this.system = system;
	}

	public String getLocalPath() {
		return localPath;
	}

	public void setLocalPath(String localPath) {
		this.localPath = localPath;
	}

	public List<String> getUser() {
		return user;
	}

	public void setUser(List<String> user) {
		this.user = user;
	}

	public TestUser getTestUser() {
		return testUser;
	}

	public void setTestUser(TestUser testUser) {
		this.testUser = testUser;
	}

	
}
2) 在DemoApplication啓動類中注入bean,完整代碼如下:
package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

import com.example.properties.ConfigProperties;

@SpringBootApplication
@MapperScan("com.*.mapper")//掃描該包下接口
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
	
	@Bean
	@ConfigurationProperties(prefix="com.conf.group",locations="classpath:config.properties")
	public ConfigProperties configProperties(){
		return new ConfigProperties();
	}
}
啓動測試:http://localhost:8088/spring-boot/properties/conf

查看返回結果:

{
  "status": "true",
  "msg": "自定義properties文件,定義多個屬性",
  "result": {
    "conf": {
      "name": "group",
      "number": 5,
      "system": "人員管理",
      "localPath": "127.0.0.1:8088",
      "user": [
        "Lucy",
        "Susan",
        "Joly"
      ],
      "testUser": {
        "name": "user_name",
        "age": 22,
        "gender": "M"
      }
    }
  }
}
可以看到,這裏的結果跟上面是一樣的,說明注入屬性成功。

===========================================================================

關於自定義屬性的學習就到此結束,參考博文:http://412887952-qq-com.iteye.com/blog/2311017

下篇我們將學習,SpringBoot 學習記錄(九): Email
























發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章