方式一、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方法
}
本文介绍如何在Spring Boot中使用@PropertySource和@ConfigurationProperties注解实现配置文件自动映射,包括Controller和实体类的配置,以及优化的ServerSettings实例配置。
8352

被折叠的 条评论
为什么被折叠?



