1、@ConfigurationProperties
将配置文件中配置的每一个属性的值,映射到这个组件中,@ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定; prefix = “person”:配置文件中哪个下面的所有属性进行一一映射.只有这个组件是容器中的组件,才能有@ConfigurationProperties功能;@ConfigurationProperties(prefix = “person”)默认从全局配置文件中获取值;
person:
name: zhangsan
age: 18
birth:2017-09-01
yaml文件也可以是properties文件,但是全局配置文件
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {
......
}
2、@PropertySource
用于加载指定的properties文件,不一定所有的配置都写在配置文件里,用于加载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
@PropertySource(value = {"classpath:person.properties"})
@Component
public class Person {
......
}
value的值为类路径下(class文件夹)的配置文件的位置
3、@ImportResource
用于导入spring里的xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>
@ImportResource(locations={"classpath:beans.xml"})
public class Person {
......
}
4、@bean
SpringBoot推荐给容器中添加组件的方式;推荐使用全注解的方式
1、配置类@Configuration------>Spring配置文件
2、使用@Bean给容器中添加组件
@Configuration
public class MyAppConfig {
//将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
@Bean
public HelloService helloService02(){
System.out.println("配置类@Bean给容器中添加组件了...");
return new HelloService();
}
}