springboot 注入properties 属性值
- 在之前注入属性值我们都是采用xml方式
<context:property-placeholder location="classpath:xxxx.properties" ignore-unresolvable="true"/>
- 采用注解方式在类上@PropertySSource 指定文件位置然后通过@Value注入属性值
在springboot 中
- 我们可以直接采用@Value方式
- 或者自定义properties文件然后根据注解@ConfigurationProperties 注解 加载文件内容
application.properties 文件内容
book.name=html book.price=38
根据@Value注入
@Controller
public class Test {
@Value("${book.name}")
private String name;
@Value("book.price")
private String price;
@RequestMapping("index")
public String Test(){
System.out.println( price + "---" + name );
return "index";
}
}
访问url 后我们可以在控制台查看
根据注解@ ConfigurationProperties
- 自定义book.properties
book.name=html book.price=38
- 自定义的Book类
@Component
@ConfigurationProperties(prefix = "book")
public class Book {
private String name;
private String price;
public String getName() {
return name;
}
public String getPrice() {
return price;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(String price) {
this.price = price;
}
}
- 然后注入访问查看
@Controller
public class Test {
@Autowired
private Book book;
@RequestMapping("index")
public String Test(){
System.out.println(book.getName() + "--- >" + book.getPrice());
return "index";
}
}
- 查看结果
为什么是null??
查了很多资料后才发现springboot高本版本(我个人这个版本是2.0)将 location 这个属性去掉了,这里不能指定自定义的文件位置
通过这个注解指定一下位置
@PropertySource(value = "book.properties")
还是不可以,值还是为 null 郁闷中。。。。。
需要手动加注解@Value 注入了
@Component
public class Book {
@Value("${name}")
private String name;
@Value("${price}")
private String price;
运行了一下成功
总结
低版本可以用注解
@ConfigurationProperties
中 locations来指定文件路径
然而高版本没有locations此属性 得用
@PropertySource
来指定文件位置