四、@PropertySource&@ImportResource&@Bean详解。以及配置文件占位符

application.properties和 application.yml是全局配置文件,所有的配置都写在这里就不太合适 了。所以
1.@PropertySource:加载指定的配置文件

@PropertySource(value = {"classpath:person.properties"})
@Component
@Component @ConfigurationProperties(prefix = "person")
public class Person {  
     /**      *       *   
            
    *    
   */    
  //lastName必须是邮箱格式  
  // @Email  
   //@Value("${person.last‐name}")   
  private String lastName;     //@Value("#{11*2}")  
  private Integer age;     //@Value("true")   
  private Boolean boss;

person.properties

person.last-name=李四
person.age=12
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15

2.@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效; Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别; 想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上(比如放在App类似) 但是这种方式官方并不推荐


(I1AZ25_1B9UAJMA7O6M~S1.png
@ImportResource(locations = {"classpath:beans.xml"}) 导入Spring的配置文件让其生效

不来编写Spring的配置文件 :bean.xml





    



3.SpringBoot推荐给容器中添加组件的方式;推荐使用全注解的方式
a、配置类@Configuration------>Spring配置文件 2、使用@Bean给容器中添加组件

package com.flyz.config;

import com.flyz.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件
 *
 * 在配置文件中用标签添加组件
 *
 */
@Configuration
public class MyAppconfig {

    //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService(){
        System.out.println("配置类@Bean给容器中添加组件了...");
        return new HelloService();
    }

}



4、配置文件占位

1、随机数

 ${random.value}、${random.int}、${random.long} ${random.int(10)}、${random.int[1024,65536]}

2、占位符获取之前配置的值,如果没有可以是用:指定默认

person.last‐name=张三${random.uuid} 
person.age=${random.int} 
person.birth=2017/12/15 
person.boss=false 
person.maps.k1=v1
 person.maps.k2=14
 person.lists=a,b,c
 person.dog.name=${person.hello:hello}_dog person.dog.age=15

你可能感兴趣的:(四、@PropertySource&@ImportResource&@Bean详解。以及配置文件占位符)