在项目中,很多时候需要用到一些配置的信息,这些信息可能在测试环境和生产环境下会有 不同的配置,后面根据实际业务情况有可能还会做修改,针对这种情况,我们不能将这些配置在代码中 写死,最好就是写到配置文件中。比如可以把这些信息写到 application.yml或者application.properties 文件中。
测试在Controller中获取属性。
1.在application.yml中配置属性
server:
port: 8001 # 配置微服务的地址
url:# 订单微服务的地址
orderUrl: http://localhost:8002
2.在Controller中使用@Value注解获取属性
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class ConfigController {
@Value("${url.orderUrl}")
private String orderUrl;
@RequestMapping("/config")
public String testConfig() {
System.out.println(orderUrl);
return "success";
}
}
测试在Controller中读取带前缀的多个属性。
如果在配置文件中配置多个以相同前缀开头的属性,如果这样一个个去使用 @Value 注解引入相应的微服务地址的话,太过于繁琐,也不科学。我们可以通过使用@ConfigurationProperties来解析前缀。
1.在application.yml配置带前缀的属性
upload:
userFileFile: \user\upload
systemFilePath: \sys\upload
logFilePath: \log\upload
2.在config包下,配置一个前缀解析类。
package com.oracle.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "upload")
public class UploadPathConfiguration {
private String userFileFile;
private String systemFilePath;
private String logFilePath;
}
注意:确保在pom.xml中添加有配置解析依赖。
<!--springboot解析配置类的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
在Controller中测试。
package com.oracle.controller;
import com.oracle.config.UploadPathConfiguration;
import com.oracle.json.JsonData;
import com.oracle.json.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("upload")
public class UploadController {
@Resource
private UploadPathConfiguration uploadPathConfiguration;
@GetMapping("/")
//执行文件上传
public R doUpload(String fileName) {
System.out.println("用户文件的上传路径是:" + uploadPathConfiguration.getUserFileFile());
System.out.println("系统文件的上传路径是:" + uploadPathConfiguration.getSystemFilePath());
System.out.println("日志文件的上传路径是:" + uploadPathConfiguration.getLogFilePath());
//表示上传成功。
return R.ok("uploadSuccess");
}
}
控制台输出效果如下:
