7 @propertySource 和@ImportResource注解和@bean 配置文件占位符

总览

1 @propertySource 注解(更改默认的配置文件,加载某个类中)

2将一个类作为bean添加进去容器之中? @ ImportResource 注解

3 配置文件占位符

github地址 https://github.com/frankg1/springboot-yaml-test

 

 

1 @PropertySource 注解

 

@ConfigurationProperties注解默认是加载全局配置文件,但是不是所有的东西都写在群居配置文件之中(加此注解的类必须是容器组件,所以需要加上@Component)但是在ConfigurationProperties注解之上加上PropertySource注解,就可以吧默认的全局配置文件改成指定配置文件。

 

在resources目录下新建person.properties配置文件,将配置信息全部放到这里去,那就行了。

  1. @PropertySource(value={"classpath:person.properties"})  
  2. @Component  
  3. @ConfigurationProperties(prefix = "person")  
  4.   
  5. public class Person {  
  6.     //@Value("${person.name}")  
  7.     private String name;  
  8.     //@Value("${person.age}")  
  9.     private Integer age;  
  10.     private boolean boss;  
  11.     private Date birth;  
  12.     private Map<String,Object> maps;  
  13.     private List<Object> lists;  
  14.     private Dog dog;  

2 如何将一个类作为bean添加进去容器之中? @ ImportResource 注解

 

首先在resource下创建bean.xml

  1. <bean id="testBean" class="com.example.springbootyamltest.bean.Dog"></bean>  
  2. <bean id="HelloService" class="com.example.springbootyamltest.service.HelloService" ></bean>  

然后在主程序中添加这个注解,标识将这个配置文件加载进来,

@ImportResource(locations = {"classpath:bean.xml"})

但是这不是spring boot推荐的方式 官方推荐的方式如下

推荐使用配置类的方式

 新建配置类

  1. package com.example.springbootyamltest.config;  
  2. import com.example.springbootyamltest.service.HelloService;  
  3. import org.springframework.context.annotation.Bean;  
  4. import org.springframework.context.annotation.Configuration;  
  5. /* 
  6. * @configuration 表名这是一个配置类,来提到之前的xml配置bean的方法 
  7. * xml中使用<bean></bean>这样的方法去配置bean 
  8. * */  
  9. @Configuration  
  10. public class MyConfig {  
  11.     @Bean  
  12.     //函数名就是bean id  
  13.     public HelloService helloService(){  
  14.         return new HelloService();  
  15.     }  
  16. }  

这样就行了,就可以测出来 bean是否被添加到容器之中。

 

3 配置文件占位符

3.1 随机数

${random.int}  random.uuid  random.int(10) random.int[1,10]

 

3.2 如果没有配置,可以使默认值。

        ${person.name1:noname}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值