欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring容器中添加bean的5種方式

 更新時間:2021年07月07日 11:41:25   作者:楚三木  
我們知道平時在開發(fā)中使用Spring的時候,都是將對象交由Spring去管理,那么將一個對象加入到Spring容器中,有哪些方式呢,感興趣的可以了解一下

我們知道平時在開發(fā)中使用Spring的時候,都是將對象交由Spring去管理,那么將一個對象加入到Spring容器中,有哪些方式呢,下面我就來總結(jié)一下

@Configuration + @Bean

這種方式其實,在上一篇文章已經(jīng)介紹過了,也是我們最常用的一種方式,@Configuration用來聲明一個配置類,然后使用 @Bean 注解,用于聲明一個bean,將其加入到Spring容器中。
具體代碼如下:

@Configuration
public class MyConfiguration {
    @Bean
    public Person person() {
        Person person = new Person();
        person.setName("spring");
        return person;
    }
}

@Componet + @ComponentScan

這種方式也是我們用的比較多的方式,@Componet中文譯為組件,放在類名上面,然后@ComponentScan放置在我們的配置類上,然后可以指定一個路徑,進(jìn)行掃描帶有@Componet注解的bean,然后加至容器中。

具體代碼如下:

@Component
public class Person {
    private String name;

    public String getName() {

        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

@ComponentScan(basePackages = "it.chusen.spring.*")
public class Demo1 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
    }
}

結(jié)果輸出:

Person{name='null'}

表示成功將Person放置在了IOC容器中。

@Import注解導(dǎo)入

前兩種方式,大家用的可能比較多,也是平時開發(fā)中必須要知道的,@Import注解用的可能不是特別多了,但是也是非常重要的,在進(jìn)行Spring擴(kuò)展時經(jīng)常會用到,它經(jīng)常搭配自定義注解進(jìn)行使用,然后往容器中導(dǎo)入一個配置文件。關(guān)于@Import注解,我會多介紹一點,它有三種使用方式,我會一一介紹。這是@Import注解的源碼,表示只能放置在類上。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {

    /**
   * 用于導(dǎo)入一個class文件
     * {@link Configuration @Configuration}, {@link ImportSelector},
     * {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
     */
    Class<?>[] value();

}

@Import直接導(dǎo)入類

代碼示例如下:

public class Person {
    private String name;

    public String getName() {

        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}
/**
* 直接使用@Import導(dǎo)入person類,然后嘗試從applicationContext中取,成功拿到
**/
@Import(Person.class)
public class Demo1 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
    }
}

上述代碼直接使用@Import導(dǎo)入了一個類,然后自動的就被放置在IOC容器中了。注意
我們的Person類上 就不需要任何的注解了,直接導(dǎo)入即可。

@Import + ImportSelector

其實在@Import注解的源碼中,說的已經(jīng)很清楚了,感興趣的可以看下,我們實現(xiàn)一個ImportSelector的接口,然后實現(xiàn)其中的方法,進(jìn)行導(dǎo)入。

代碼如下:

@Import(MyImportSelector.class)
public class Demo1 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
    }
}

class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{"it.chusen.spring.model.Person"};
    }
}

我自定義了一個 MyImportSelector 實現(xiàn)了 selectImports 方法,然后將我們要導(dǎo)入的類的全限定名寫在里面即可,實現(xiàn)起來也是非常簡單。

@Import + ImportBeanDefinitionRegistrar

這種方式也需要我們實現(xiàn) ImportBeanDefinitionRegistrar 中的方法,具體代碼如下:

@Import(MyImportBeanDefinitionRegistrar.class)
public class Demo1 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
    }
}

class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 構(gòu)建一個beanDefinition, 關(guān)于beanDefinition我后續(xù)會介紹,可以簡單理解為bean的定義.
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class).getBeanDefinition();
        // 將beanDefinition注冊到Ioc容器中.
        registry.registerBeanDefinition("person", beanDefinition);
    }
}

上述實現(xiàn)其實和Import的第二種方式差不多,都需要去實現(xiàn)接口,然后進(jìn)行導(dǎo)入。接觸到了一個新的概念,BeanDefinition,可以簡單理解為bean的定義(bean的元數(shù)據(jù)),也是需要放在IOC容器中進(jìn)行管理的,先有bean的元數(shù)據(jù),applicationContext再根據(jù)bean的元數(shù)據(jù)去創(chuàng)建Bean。

@Import + DeferredImportSelector

這種方式也需要我們進(jìn)行實現(xiàn)接口,其實它和@Import的第二種方式差不多,DeferredImportSelector 它是 ImportSelector 的子接口,所以實現(xiàn)的方法和第二種無異。只是Spring的處理方式不同,它和Spring Boot中的自動導(dǎo)入配置文件 延遲導(dǎo)入有關(guān),非常重要。使用方式如下:

@Import(MyDeferredImportSelector.class)
public class Demo1 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
    }
}
class MyDeferredImportSelector implements DeferredImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        // 也是直接將Person的全限定名放進(jìn)去
        return new String[]{Person.class.getName()};
    }
}

關(guān)于@Import注解的使用方式,大概就以上三種,當(dāng)然它還可以搭配@Configuration注解使用,用于導(dǎo)入一個配置類。

使用FactoryBean接口

FactoryBean接口和BeanFactory千萬不要弄混了,從名字其實可以大概的區(qū)分開,F(xiàn)actoryBean, 后綴為bean,那么它其實就是一個bean, BeanFactory,顧名思義 bean工廠,它是IOC容器的頂級接口,這倆接口其實都很重要。
代碼示例:

@Configuration
public class Demo1 {
    @Bean
    public PersonFactoryBean personFactoryBean() {
        return new PersonFactoryBean();
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
    }
}

class PersonFactoryBean implements FactoryBean<Person> {

    /**
     *  直接new出來Person進(jìn)行返回.
     */
    @Override
    public Person getObject() throws Exception {
        return new Person();
    }
    /**
     *  指定返回bean的類型.
     */
    @Override
    public Class<?> getObjectType() {
        return Person.class;
    }
}

上述代碼,我使用@Configuration + @Bean的方式將 PersonFactoryBean 加入到容器中,注意,我沒有向容器中注入 Person, 而是直接注入的 PersonFactoryBean 然后從容器中拿Person這個類型的bean,成功運行。

使用 BeanDefinitionRegistryPostProcessor

其實這種方式也是利用到了 BeanDefinitionRegistry,在Spring容器啟動的時候會執(zhí)行 BeanDefinitionRegistryPostProcessor 的 postProcessBeanDefinitionRegistry 方法,大概意思就是等beanDefinition加載完畢之后,對beanDefinition進(jìn)行后置處理,可以在此進(jìn)行調(diào)整IOC容器中的beanDefinition,從而干擾到后面進(jìn)行初始化bean。

具體代碼如下:

public class Demo1 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        MyBeanDefinitionRegistryPostProcessor beanDefinitionRegistryPostProcessor = new MyBeanDefinitionRegistryPostProcessor();
        applicationContext.addBeanFactoryPostProcessor(beanDefinitionRegistryPostProcessor);
        applicationContext.refresh();
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
    }
}

class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class).getBeanDefinition();
        registry.registerBeanDefinition("person", beanDefinition);
    }
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}

上述代碼中,我們手動向beanDefinitionRegistry中注冊了person的BeanDefinition。最終成功將person加入到applicationContext中,上述的幾種方式的具體原理,我后面會進(jìn)行介紹。

小結(jié)

介紹了向spring容器中加入bean的幾種方式.

  • @Configuration + @Bean
  • @ComponentScan + @Component
  • @Import 配合接口進(jìn)行導(dǎo)入
  • 使用FactoryBean。
  • 實現(xiàn)BeanDefinitionRegistryPostProcessor進(jìn)行后置處理。

其實向Spring中加入bean的方式有很多種,這里簡要介紹了上面這幾種。

到此這篇關(guān)于Spring容器中添加bean的5種方式的文章就介紹到這了,更多相關(guān)Spring添加bean內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • 深入解析Java的Spring框架中bean的依賴注入

    深入解析Java的Spring框架中bean的依賴注入

    這篇文章主要介紹了Java的Spring框架中bean的依賴注入,講解了以構(gòu)造函數(shù)為基礎(chǔ)的依賴注入和基于setter方法的依賴注入的方式,需要的朋友可以參考下
    2015-12-12
  • IDEA中切換不同版本的JDK的詳細(xì)教程(超管用)

    IDEA中切換不同版本的JDK的詳細(xì)教程(超管用)

    這篇文章主要介紹了IDEA中切換不同版本的JDK的詳細(xì)教程(超管用),本文通過步驟詳解給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-09-09
  • Java?MapStruct優(yōu)雅地實現(xiàn)對象轉(zhuǎn)換

    Java?MapStruct優(yōu)雅地實現(xiàn)對象轉(zhuǎn)換

    MapSturct?是一個生成類型安全,高性能且無依賴的?JavaBean?映射代碼的注解處理器,用它可以輕松實現(xiàn)對象轉(zhuǎn)換,下面就來和大家聊聊具體操作吧
    2023-06-06
  • java高并發(fā)鎖的3種實現(xiàn)示例代碼

    java高并發(fā)鎖的3種實現(xiàn)示例代碼

    本篇文章主要介紹了java高并發(fā)鎖的3種實現(xiàn)示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • Servlet虛擬路徑映射配置詳解

    Servlet虛擬路徑映射配置詳解

    這篇文章主要介紹了Servlet虛擬路徑映射配置詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02
  • SpringCloud?中防止繞過網(wǎng)關(guān)請求直接訪問后端服務(wù)的解決方法

    SpringCloud?中防止繞過網(wǎng)關(guān)請求直接訪問后端服務(wù)的解決方法

    這篇文章主要介紹了SpringCloud中如何防止繞過網(wǎng)關(guān)請求直接訪問后端服務(wù),本文給大家分享三種解決方案,需要的朋友可以參考下
    2023-06-06
  • Java的數(shù)據(jù)類型和參數(shù)傳遞(詳解)

    Java的數(shù)據(jù)類型和參數(shù)傳遞(詳解)

    下面小編就為大家?guī)硪黄狫ava的數(shù)據(jù)類型和參數(shù)傳遞(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-07-07
  • Java?LocalTime的常用時間操作總結(jié)

    Java?LocalTime的常用時間操作總結(jié)

    日常開發(fā)中,?我們會經(jīng)常遇到時間的運算,?操作,?格式化等,?這篇文章主要為大家詳細(xì)介紹了LocalTime的常用時間操作,感興趣的小伙伴可以了解一下
    2023-11-11
  • java中用ObjectMapper類實現(xiàn)Json與bean的轉(zhuǎn)換示例

    java中用ObjectMapper類實現(xiàn)Json與bean的轉(zhuǎn)換示例

    這篇文章主要給大家介紹了關(guān)于在java中用ObjectMapper類實現(xiàn)Json與bean轉(zhuǎn)換的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面跟著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-08-08
  • 深入理解Java 線程池

    深入理解Java 線程池

    這篇文章主要介紹了Java 線程池的相關(guān)資料,文中講解非常細(xì)致,幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07

最新評論