使用@Value注解读取
读取properties配置文件时,默认读取的是application.properties。
在application.properties文件中加入自定义的属性,例如:
# 自定义属性 (用于测试@Value注解:来获取自定义属性的值)
book.author=zhanghong
book.name=Spring Boot
java类:
package com.example.mybatisplusdemo.test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author: kevin_zhang
* @date: 2020/1/11 0011 22:00
* @Description: 获取自定义属性的值
*/
@Component
public class TestValue {
@Value("${book.author}")
public String author;
@Value("${book.name}")
public String name;
}
Controll层:
@RestController
@RequestMapping("/book")
public class BookController {
@Autowired
private TestValue testValue;
@RequestMapping(value = "/gateway")
public String gateway() {
return "get properties value by ''@Value'' :" +
//1、使用@Value注解读取
" name=" + testValue.name +
" , age=" + testValue.author;
}
测试结果如下:
注意:当自定义属性较多时,可以用下面的方式来进行简化,不用在每个属性上都加上@Value注解,只需要在类上加上注解@ConfigurationProperties(prefix = “book”),指明属性的前缀,然后就会自动匹配后面的属性,但使用这个注解需要定义的类中加上getter()和Setter()方法;
package com.example.mybatisplusdemo.test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author: kevin_zhang
* @date: 2020/1/11 0011 22:00
* @Description: 获取自定义属性的值
*/
@Component
@ConfigurationProperties(prefix = "book")
public class TestValue {
public String author;
public String name;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
得到的测试结果跟上面一样