@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測試類中進行測試,可以將容器中的類自動依賴注入進來。
在這裏插入圖片描述

二、@ImportResource

1. 註解用法

@ImportResource:導入Spring的配置文件,讓配置文件裏面的內容生效;

Spring Boot 不能自動加載 Spring 的配置文件,我們自己編寫的配置文件,也不能自動識別;可以將@ImportResource註解標註在一個配置類上,引入spring 配置文件使其生效。

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

2. 測試

(1)編寫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.atguigu.springboot.service.HelloService"></bean>
</beans>

(2)在測試類中測試容器中是否存在 bean。結果顯示:在引入 @ImportResource(locations = {“classpath:beans.xml”}) 之前,不存在 helloService , 引入註解後存在helloService。
在這裏插入圖片描述

三、@Bean

@ImportResource 註解是通過在 spring.xml 中配置bean,再將配置文件引入的方式將組件添加到容器中。而 SpringBoot推薦使用全註解的方式
給容器中添加組件;
用到兩個註解:

  • @Configuration 指明該類是一個配置類------>其作用與Spring配置文件類似;
  • @Bean 給容器中添加組件,將該註解加載方法上,方法名就是這個組件添加到容器後的默認id。
/**
 * @Configuration:指明當前類是一個配置類;就是來替代之前的Spring配置文件;
 * 以前在配置文件中用<bean><bean/>標籤添加組件,現在用 @Bean 註解的方式
 */
@Configuration
public class MyAppConfig {

    //將方法的返回值添加到容器中;方法名就是容器中這個組件的默認id。
    @Bean
    public HelloService helloService02(){
        System.out.println("配置類@Bean給容器中添加組件了...");
        return new HelloService();
    }
}

測試方法同上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章