SpringBoot注解配置文件自动映射到属性和实体类(解决硬编码问题)
配置文件自动映射解决的问题
可以从配置文件自定义属性值,通过注解自动映射到属性或者实体类中,解决代码中的硬编码问题
配置文件自动映射到属性
以一个上传文件控制类中需要注入上传图片路径属性为例:
1.在Controller
类上加配置文件路径注解:
这里直接在application.properties中直接自定义的需要注入的配置属性信息,所以就引入application.properties
@PropertySource({"classpath:application.properties"})
2.在application.properties
配置文件中自定义需要注入的属性:
3.在Controller
中编写被注入属性:
@Value("${web.file.path}")
private String filePath;
配置文件自动映射到实体类
配置文件自动映射到属性只能在Controller类中注入
为了解决这种局限性
可以配置文件自动映射到实体类
然后再依赖注入实体类
1.定义一个用作映射的实体类ServerSetting.java:
package com.springboot20.xdclass.springboot.demo2.setting;
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:resources.properties"})
@ConfigurationProperties
public class ServerSetting {
@Value("${test.domain}")
private String domain;
@Value("${test.name}")
private String name;
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
注意:以下三个类注解
2.定义一个配置信息文件resources.properties:
3.ServerSetting.java中用@Value给属性配文件中的值:
4.编写单元测试类TestSetting.java:
package com.springboot20.xdclass.springboot.demo2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.springboot20.xdclass.springboot.demo2.setting.ServerSetting;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestSetting {
@Autowired
private ServerSetting serverSetting;//注入ServerSetting
@Test
public void testSetting(){
System.out.println(serverSetting.getDomain());
System.out.println(serverSetting.getName());
}
}
5.单元测试结果:
控制台输出结果:
证明配置信息自动注入实体类
注意以下这种情况ServerSetting.java中用@Value给属性配置文件中的值可以省略:
resources.properties配置文件中:
执行单元测试结果一致