Spring 配置文件的使用

本文介绍如何在Spring Boot中使用@PropertySource和@ConfigurationProperties注解实现配置文件自动映射,包括Controller和实体类的配置,以及优化的ServerSettings实例配置。
摘要由CSDN通过智能技术生成

方式一、Controller上面配置

简介:讲解使用@value注解配置文件自动映射到属性和实体类

1、配置文件加载

方式一

1、Controller上面配置

@PropertySource({”classpath:resource.properties”})

2、增加属性

@Value(“${test.name}”)

private String name;

举例

上篇的文件上传的地址我是写死的。

这样显然不科学,这里改成写在1.application.properties配置文件里。

#文件上传路径配置

web.file.path=C:/Users/chenww/Desktop/springbootstudy/springbootstudy/src/main/resources/static/images/

2在FileController 类中

@Controller

@PropertySource({"classpath:application.properties"})

public class FileController {
//文件放在项目的images下

// private String filePath = "C:\\Users\\chenww\\Desktop\\springbootstudy\\springbootstudy\\src\\main\\resources\\static\\images\\";

@Value("${web.file.path}")

private String filePath;

总结:

1:@PropertySource代表读取哪个文件

2:@Value通过key得到value值

方式二:实体类配置文件

步骤:

1、添加 @Component 注解;

2、使用@PropertySource 注解指定配置文件位置;

3、使用 @ConfigurationProperties 注解,设置相关属性;

4、必须 通过注入IOC对象Resource 进来 , 才能在类中使用获取的配置文件值。

@Autowired

private ServerSettings serverSettings;

案例:

1、在application.properties

#测试配置文件路径

test.domain=www.jincou.com

test.name=springboot

2、创建ServerSettings实体

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

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

import org.springframework.context.annotation.PropertySource;

import org.springframework.stereotype.Component;

//服务器配置

@Component

@PropertySource({"classpath:application.properties"})

@ConfigurationProperties

public class ServerSettings {
//名称test.domain是key值

@Value("${test.domain}")

private String name;

//域名地址

@Value("${test.name}")

private String domain;

//提供set和get方法

}

三创建GetController

import com.jincou.model.ServerSettings;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

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

@RestController

public class GetController {
//需要注入

@Autowired

private ServerSettings serverSettings;

@GetMapping("/v1/test_properties")

public Object testPeroperties(){
return serverSettings;

}

}

页面效果

其实上面还可以做个优化:

创建ServerSettings实体

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

import org.springframework.context.annotation.PropertySource;

import org.springframework.stereotype.Component;

//服务器配置

@Component

@PropertySource({"classpath:application.properties"})

@ConfigurationProperties(prefix="test")

//这里加了个test前缀

public class ServerSettings {
//这是不需要写vlaue标签,只要text.name去掉前缀test后的name和这里name相同,就会自动赋值

private String name;

//域名地址

private String domain;

//提供set和get方法

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值