Spring如何获取配置在application.properties文件中属性的值?


本文摘自CSDN-曲健磊,原文地址:https://blog.csdn.net/a909301740/article/details/81448783

Spring如何获取配置application.properties文件中属性的值?

通过 @Value("${com.springboot.name}")注解的方式:

application.properties 文件的内容如下:

com.springboot.name=qujianlei

com.springboot.title=studyhadoop

com.springboot.desc=${com.springboot.name} work hard ${com.springboot.title}

com.springboot.random.string=${random.value}

com.springboot.random.int=${random.int}

com.springboot.random.long=${random.long}

比方说我们现在要在 Controller 中获取 com.springboot.name 的值,只需像下面这样既可:

package com.qjl.bootstart.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.qjl.bootstart.yml.User;
import com.qjl.bootstart.yml.YmlUtil;

/**
 * 类名称:SpringMVC的控制器
 * 全限定性类名: com.qjl.bootstart.controller.BootController
 * @author 曲健磊
 * @date 2018年8月4日上午10:38:23
 * @version V1.0
 */
@RestController
@RequestMapping("/boot")
public class BootController {
	
	@Value("${com.springboot.name}")
	private String name;
	
	@Value("${com.springboot.title}")
	private String title;
	
	@Value("${com.springboot.desc}")
	private String desc;
	
	@Value("${com.springboot.random.string}")
	private String str;
	
	@Value("${com.springboot.random.int}")
	private Integer integer;
	
	@Value("${com.springboot.random.long}")
	private Long _long;
	
	@RequestMapping("/hello")
	public String boot() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("hello SrpingBoot properties<br/>");
		buffer.append("[").append(name).append("]<br/>");
		buffer.append("[").append(title).append("]<br/>");
		buffer.append("[").append(desc).append("]<br/>");
		return buffer.toString();
	}
	
	@RequestMapping("/random")
	public String testRandom() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("hello SrpingBoot random<br/>");
		buffer.append("[").append(str).append("]<br/>");
		buffer.append("[").append(integer).append("]<br/>");
		buffer.append("[").append(_long).append("]<br/>");
		return buffer.toString();
	}
}

相关阅读 >>

spring如何获取配置在application.properties文件中属性的值?

spring事务管理与查询是否需要事务以及可重复读的问题

springspringmvc、springboot和springcloud的区别

使用spring4实现websocket连接

使用spring4实现websocket连接(二)

更多相关阅读请进入《spring》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...