栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot读取配置文件的三种方式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot读取配置文件的三种方式

项目中springboot读取配置文件的三种方式:

1.使用Environment

2.使用@Value

3.使用@ConfigurationProperties注解映射到bean中,定义一个User对象里面有name和age属性,在配置文件里使用spring.user作为prefix,为User增加对应注解即可

配置文件: 

#===application.properties文件
spring.profiles.active=dev
#===application-dev.properties文件
server.port=8088

#user的属性配置
spring.user.name=wahaha
spring.user.age=30
package com.blackbird.demo.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.blackbird.config.User;

@RestController
public class ConfigController {

	//读取配置方式一
	@Autowired
	private Environment env;
	
	//读取配置方式二,8080为默认值
	@Value("${server.port:8080}")
	private String port;
	
	//读取配置第三种方式,将属性注入到实体类中
//	@ConfigurationProperties
	@Autowired
	private User user;
	
	@GetMapping("/config")
	public Object config() {
		Map config = new HashMap<>();
		config.put("profiles", env.getProperty("spring.profiles.active"));
		config.put("port", port);
		config.put("user.name", user.getName());
		config.put("user.age", user.getAge());
		return config;
	} 
	
}
package com.blackbird.config;

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

import lombok.Data;

@Data
@Configuration
@ConfigurationProperties(prefix="spring.user")
public class User {

	private String name;
	private String age;
	
}

浏览器请求结果:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/358201.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号