@PropertySource & @ImportResource & @Bean

@PropertySource&@ImportResource&@Bean

一、@PropertySource:加载指定的properties配置文件;

1. 注解用法:

@ConfigurationProperties 注解只能将全局配置文件(application.properties 或 application.yml)的值映射到javaBean上, 如果是自定义的 properties 配置文件,Spring Boot 无法映射。在需要映射的类上加**@PropertySource** 注解引入配置文件, SpringBoot 会将配置文件中的属性值绑定到类中的字段上,即为 javaBean 注入值。


@PropertySource(value = {"classpath:person.properties"})
@Component
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;

2. 测试:

在springboot测试类中进行测试,可以将容器中的类自动依赖注入进来。
@PropertySource & @ImportResource & @Bean_第1张图片

二、@ImportResource

1. 注解用法

@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;

Spring Boot 不能自动加载 Spring 的配置文件,我们自己编写的配置文件,也不能自动识别;可以将@ImportResource注解标注在一个配置类上,引入spring 配置文件使其生效。

@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class TmpExecutorApplication {

2. 测试

(1)编写Spring的配置文件


<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>

(2)在测试类中测试容器中是否存在 bean。结果显示:在引入 @ImportResource(locations = {“classpath:beans.xml”}) 之前,不存在 helloService , 引入注解后存在helloService。
@PropertySource & @ImportResource & @Bean_第2张图片

三、@Bean

@ImportResource 注解是通过在 spring.xml 中配置bean,再将配置文件引入的方式将组件添加到容器中。而 SpringBoot推荐使用全注解的方式
给容器中添加组件;
用到两个注解:

  • @Configuration 指明该类是一个配置类------>其作用与Spring配置文件类似;
  • @Bean 给容器中添加组件,将该注解加载方法上,方法名就是这个组件添加到容器后的默认id。
/**
 * @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件;
 * 以前在配置文件中用标签添加组件,现在用 @Bean 注解的方式
 */
@Configuration
public class MyAppConfig {

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

测试方法同上。

你可能感兴趣的:(Spring,Boot)