一:@PropertySource
- 作用:加载指定的配置文件
- 比如在类路径下新增一个person.properties
- 加载配置文件
/*
将配置文件的每一个属性值映射到这个组件中
@ConfigurationProperties:告诉springBoot将本类中所有属性和配置文件中的相关配置进行绑定
prefix = "person" :配置文件中那个下面的属性进行一一映射
只有这个组件是容器中的组件,才能使用容器提供的ConfigurationProperties功能
@ConfigurationProperties(prefix = "person")默认从全局配置文件中取值
*/
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:person.properties"})
@Component
//@Validated
public class Person {
//@Value("${person.lastName}")
private String lastName;
// @Value("#{22*3}")
private Integer age;
// @Value("true")
private String boss;
private Date birth;
private Map<String,Object> maps;
private List<String> lists;
private Dog dog;
二:@ImportResource
- 作用:导入Spring配置文件,让配置文件的内容生效
SpringBoot里面没有Spring的配置文件,我们自己编写的配置文件也不能识别,想让Spring的配置文件生效,加载进来
使用@ImportResource标注在一个配置类上
- 新建一个beans.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.dhx.demo1.service.HelloService"></bean>
</beans>
- 需要在配置类加上才能@ImportResource,才能加入到spring配置文件生效
@ImportResource(locations = {"classpath:beans.xml"})
不来编写spring的配置文件
<?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.dhx.demo1.service.HelloService"></bean>
</beans>
- 测试
@Autowired
ApplicationContext ioc;
@Test
void testHelloService(){
boolean b= ioc.containsBean("helloService");
System.out.println(b);
}
三:@Bean
- 作用:SpringBoot推荐给容器中添加组件的方式,推荐使用全注解的方式
- 配置类------spring配置文件
- 使用@Bean给容器中添加组件
/*
@Configuration:指名当前类是一个配置类,就是来替代之前的Spring配置文件的
配置文件中使用<bean></bean>标签添加组件
*/
@Configuration
public class MyAppConfig {
//将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名
@Bean
public HelloService helloService(){
System.out.println("添加容器到组件中");
return new HelloService();
}
}