1. 程式人生 > 其它 >@ConfigurationProperties註解將配置檔案引數轉化給Bean屬性

@ConfigurationProperties註解將配置檔案引數轉化給Bean屬性

技術標籤:Springspringjava

@ConfigurationProperties 註解將配置檔案引數轉化給Bean屬性

一、application.properties引數配置

website.ip=192.168.10.112
website.port=8725
website.name=catlina.com

二、建立實體類 WebSiteProperties ,設定屬性ip、port、name。在類上配置@Configuration 和 @ConfigurationProperties(prefix = “website”)註解。
@ConfigurationProperties配置字首值與application.properties裡引數字首保持一致。新增類的setter、getter方法

package com.jvli.project.config;

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

@Configuration
@ConfigurationProperties(prefix = "website")
public class WebSiteProperties {
	
	private String ip;
	
	private
Integer port; private String name; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getName() { return name; } public void
setName(String name) { this.name = name; } @Override public String toString() { return "WebSiteProperties [ip=" + ip + ", port=" + port + ", name=" + name + "]"; } }

三、建立Controller測試,注入WebSiteProperties 。此時我們便可以任性的運用配置檔案裡的引數了。實際開發中結合自己的業務實現不同的應用場景。

package com.jvli.project.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.jvli.project.config.WebSiteProperties;


@RestController
@RequestMapping("/test")
public class TestController {

	@Autowired
	private WebSiteProperties webSiteProperties;
	
	@RequestMapping(value = "/print/property",method = RequestMethod.GET)
	public Map<String, Object> printProperty() {
		System.out.println(webSiteProperties);
		Map<String, Object> webSiteMap = new HashMap<>();
		webSiteMap.put("ip", webSiteProperties.getIp());
		webSiteMap.put("port", webSiteProperties.getPort());
		webSiteMap.put("name", webSiteProperties.getName());
		return webSiteMap;
	}
	}

檢視控制檯和postman呼叫返回結果
在這裡插入圖片描述
在這裡插入圖片描述