1.application.yml配置文件中配置好需要映射的值
guns:
file-upload-path: d:/tmp //文件上传地址
2.创建实体类
@ConfigurationProperties(prefix = "guns") prefix:指定需要映射的配置文件 guns:和yml文件中保持一致
@Component:把实体类交给spring管理
package com.stylefeng.guns.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.Map;
import static com.stylefeng.guns.core.util.ToolUtil.getTempPath;
import static com.stylefeng.guns.core.util.ToolUtil.isEmpty;
/**
* guns项目配置
*
* @author stylefeng
* @Date 2017/5/23 22:31
*/
@Component
@ConfigurationProperties(prefix = GunsProperties.PREFIX)
public class GunsProperties {
private String fileUploadPath; //下划线转驼峰命名
/**
* session 失效时间(默认为30分钟 单位:秒)
*/
private Integer sessionInvalidateTime = 30 * 60;
/**
* session 验证失效时间(默认为15分钟 单位:秒)
*/
private Integer sessionValidationInterval = 15 * 60;
public String getFileUploadPath() {
//如果没有写文件上传路径,保存到临时目录
if (isEmpty(fileUploadPath)) {
return getTempPath();
} else {
//判断有没有结尾符,没有得加上
if (!fileUploadPath.endsWith(File.separator)) {
fileUploadPath = fileUploadPath + File.separator;
}
//判断目录存不存在,不存在得加上
if (!haveCreatePath) {
File file = new File(fileUploadPath);
file.mkdirs();
haveCreatePath = true;
}
return fileUploadPath;
}
}
public void setFileUploadPath(String fileUploadPath) {
this.fileUploadPath = fileUploadPath;
}
}
3.注入使用
//注入实体类
@Autowired
private GunsProperties gunsProperties;
//调用
o2oMerchantPicture.setPicPath(gunsProperties.getFileUploadPath());
4.application.properties
connection.username=admin
connection.password=admin
connection.remoteAddress=localhost
5.实体类
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
private String username;
private String remoteAddress;
private String password ;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRemoteAddress() {
return remoteAddress;
}
public void setRemoteAddress(String remoteAddress) {
this.remoteAddress = remoteAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
我们还可以把@ConfigurationProperties还可以直接定义在@bean的注解上,这是bean实体类就不用@Component和@ConfigurationProperties了
@SpringBootApplication
public class DemoApplication{
//...
@Bean
@ConfigurationProperties(prefix = "connection")
public ConnectionSettings connectionSettings(){
return new ConnectionSettings();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
6.注入使用
@Controller
@RequestMapping("/test")
public class TaskController {
@Autowired ConnectionSettings conn;
@RequestMapping(value ="/dhi")
public String hellTask(){
String userName = conn.getUsername();
return "hello task !!";
}
}