springboot 基于properties 属性 的常规配置

springboot  注入properties 属性值

  • 在之前注入属性值我们都是采用xml方式

<context:property-placeholder location="classpath:xxxx.properties" ignore-unresolvable="true"/>

  • 采用注解方式在类上@PropertySSource 指定文件位置然后通过@Value注入属性值

 

在springboot 中

 

  1. 我们可以直接采用@Value方式
  2. 或者自定义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

                                         来指定文件位置

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TizzyGoodhealth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值