@ConfigurationProperties注解将配置文件参数转化给Bean属性

@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调用返回结果
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值