您的位置:首页 > 编程语言 > Java开发

SpringBoot 使用注解将配置文件自动映射到属性和实体类

2018-07-05 18:42 956 查看

1. 属性单独映射

1. Controller上面配置

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

2. 对要配置的属性添加注解

@Value("${web.file.path}")
private String filePath;

3. 接口测试

@GetMapping("/test/property-source")
public Object testPropertySource() {
System.out.print("配置注入打印,文件路径为:" + filePath);
return filePath;
}

2. 实体类配置文件(使用配置实体类)

1. 创建配置

application.properties 文件中添加一下内容

# 测试实体类注入
test.name = shadowolf
test.domain = www.shadowolf.cn


2. 创建一个实体类 ServiceSettings.java

两个属性 name 和 domain

添加两个属性的get和set方法

3. 给类添加注解

共有三个注解:@Component、@PropertySource、@ConfigurationProperties

@ConfigurationProperties 注解可以设置 key 的前缀

@ConfigurationProperties(prefix = "test")


详细代码

// 服务器配置
@Component
@PropertySource({"classpath:application.properties"})// @ConfigurationProperties
@ConfigurationProperties(prefix = "test")public class ServiceSettings {}


4. 添加@Value注解

@Value("${name}")
private String name;
@Value("${domain}")
private String domain;


如果此处配置文件中的key与属性名意义对应,可以不加@Value注解,假如不一致,那么就需要加@Value注解进行映射

5. 使用配置实体类

用到的地方进行注入

@Autowired
private ServiceSettings serviceSettings;

@GetMapping("/test/test-properties")
public Object testProperties() {
System.out.println("serviceSettings: " + serviceSettings);
return serviceSettings;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Spring Java Spring Boot
相关文章推荐