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

Spring容器注入bean的幾種方式詳解

 更新時(shí)間:2024年01月27日 10:46:48   作者:魅Lemon  
這篇文章主要介紹了Spring容器注入bean的幾種方式詳解,@Configuration用來聲明一個(gè)配置類,然后使用 @Bean 注解,用于聲明一個(gè)bean,將其加入到Spring容器中,這種方式是我們最常用的一種,需要的朋友可以參考下

一、五種方式簡(jiǎn)介

1、常見五種方式加入Spring容器

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

2、SpringBoot屬性注入

  • @Value注解
  • @ConfigurationPropertes注解

二、五種方式具體介紹

1、@Configuration + @Bean

@Configuration用來聲明一個(gè)配置類,然后使用 @Bean 注解,用于聲明一個(gè)bean,將其加入到Spring容器中。

這種方式是我們最常用的一種

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

2、@Componet + @ComponentScan

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

// 該類在com.shawn.*包下面
@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 = "com.shawn.*")
public class Demo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo.class);
        Person bean = applicationContext.getBean(Person.class);
        //結(jié)果輸出Person{name='null'}
        System.out.println(bean);
    }
}

3、@Import注解導(dǎo)入

@Import注解用到的并不是很多,但是非常重要,在進(jìn)行Spring擴(kuò)展時(shí)經(jīng)常會(huì)用到。它通過搭配自定義注解進(jìn)行使用,然后往容器中導(dǎo)入一個(gè)配置文件。

它有四種使用方式。

@Import注解的源碼,表示只能放置在類上

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {
    /**
   * 用于導(dǎo)入一個(gè)class文件
     * {@link Configuration @Configuration}, {@link ImportSelector},
     * {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
     */
    Class<?>[] value();
}

Import直接導(dǎo)入類

直接使用@Import導(dǎo)入了一個(gè)類,然后自動(dòng)的就被放置在IOC容器中了。注意我們的Person類上 就不需要任何的注解了,直接導(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 Demo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
    }
}

@Import + ImportSelector

自定義了一個(gè)MyImportSelector 實(shí)現(xiàn)了 ImportSelector 接口,重寫selectImports方法,然后將我們要導(dǎo)入的類的全限定名寫在里面即可導(dǎo)入

@Import(MyImportSelector.class)
public class Demo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);
    }
}
class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        //這里需要具體到類名
        return new String[]{"com.shawn.Person"};
    }
}

@Import + ImportBeanDefinitionRegistrar

這種方式需要實(shí)現(xiàn) ImportBeanDefinitionRegistrar 接口中的方法。BeanDefinition可以簡(jiǎn)單理解為bean的定義(bean的元數(shù)據(jù)),也是需要放在IOC容器中進(jìn)行管理的,先有bean的元數(shù)據(jù),applicationContext再根據(jù)bean的元數(shù)據(jù)去創(chuàng)建Bean。

@Import(MyImportBeanDefinitionRegistrar.class)
public class Demo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo.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)建一個(gè)beanDefinition
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class).getBeanDefinition();
        // 將beanDefinition注冊(cè)到Ioc容器中
        registry.registerBeanDefinition("person", beanDefinition);
    }
}

@Import + DeferredImportSelector

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

@Import(MyDeferredImportSelector.class)
public class Demo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo.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()};
    }
}

上述三類還可以搭配@Configuration注解使用,用于導(dǎo)入一個(gè)配置類

4、使用FactoryBean接口

FactoryBean接口和BeanFactory不一樣,BeanFactory顧名思義 bean工廠,它是IOC容器的頂級(jí)接口。

下述代碼通過@Configuration + @Bean的方式將 PersonFactoryBean 加入到容器中,注意,我沒有向容器中注入 Person, 而是直接注入的 PersonFactoryBean 然后從容器中拿Person這個(gè)類型的bean,成功運(yùn)行。

@Configuration
public class Demo {
    @Bean
    public PersonFactoryBean personFactoryBean() {
        return new PersonFactoryBean();
    }
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo.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;
    }
}

5、使用 BeanDefinitionRegistryPostProcessor

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

下述代碼中我們手動(dòng)向beanDefinitionRegistry中注冊(cè)了person的BeanDefinition,最終成功將person加入到applicationContext中

public class Demo {
    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 {
    }
}

三、SpringBoot屬性注入

1、@Value注解注入

1.1 簡(jiǎn)單使用

## 自定義屬性
myProperty:
  name: shawn
  introduce: 這是我自定義屬性介紹
  licences: shawn,helen
  infos: "{'phone':'36xx102','address':'xx省xx市'}"

獲取從yml定義的數(shù)據(jù)

// 注意讀取的話要加入Spring容器才行
@RestController
@RequestMapping("/source")
public class SourceAction {
    @Value("${myProperty.name}")
    private String name;
    @Value("${myProperty.introduce}:匿名用戶")
    private String introduce;
    @Value("${myProperty.licences}")
    private List<String> licences;
    @Value("#{${myProperty.infos}}")
    private Map<String, String> infos;
    @RequestMapping("/show")
    public Object show() {
        Map<String, Object> map = new LinkedHashMap();
        map.put("name", name);
        map.put("introduce", introduce);
        map.put("licences", licences);
        map.put("infos", infos);
        return map;
    }
}

1.2 擴(kuò)展

${} 與 #{}的區(qū)別

#{…} 主要用于加載外部屬性文件中的值${…} 用于執(zhí)行SpEl表達(dá)式,并將內(nèi)容賦值給屬性#{…} 和 $ {…} 可以混合使用,但是必須#{}外面,${}在里面

// 注入String@Value("${populate.string2:}")  // 默認(rèn)值是空字符串""private String stringV;@Value("${populate.string:null}")  // 默認(rèn)值是nullprivate String stringV2;@Value("${populate.string:defaultValue}")  // 默認(rèn)值是"defaultValue"private String stringV3;//注入Array@Value("${populate.array:}") // 默認(rèn)值是[]private String[] array;//注入List@Value("${populate.list:}")  // 默認(rèn)值是空List,[]private List<String> list0;@Value("#{'${populate.list:}'.split(',')}") // 默認(rèn)值是包含一個(gè)空字符串的List [""]private List<String> list1;@Value("${populate.list:l1,l2,l3}")  // 默認(rèn)值是[l1,l2,l3]private List<String> list2;@Value("#{'${populate.list:l1,l2,l3}'.split(',')}") // 默認(rèn)值是[l1,l2,l3]private List<String> list3;@Value("#{'${populate.list:,}'.split(',')}") // 默認(rèn)值是空List,[]private List<String> list4;//注入Map@Value("#{${populate.map:{}}}")    // 默認(rèn)值是nullprivate Map<String,String> map;@Value("#{${populate.map:null}}}")  // 默認(rèn)值是nullprivate Map<String, String> map2;@Value("#{${populate.map:{k1:'v1',k2:'v2'}}}")  // 默認(rèn)值是{"k1":"v1","k2":"v2"}private Map<String, String> map3;@Value("#{${populate.mapList:{}}}")    // 值為{"key1":["v11","v12"],"key2":["v21","v22"],"key3":["v31","v32"]}private Map<String,List<String>> mapList; 

2、@ConfigurationProperties注解批量注入屬性

yml配置文件,注意@Value注解獲取會(huì)報(bào)錯(cuò)

#{…} 主要用于加載外部屬性文件中的值
${…} 用于執(zhí)行SpEl表達(dá)式,并將內(nèi)容賦值給屬性
#{…} 和 $ {…} 可以混合使用,但是必須#{}外面,${}在里面

Spring進(jìn)行獲取

// 注入String
@Value("${populate.string2:}")  // 默認(rèn)值是空字符串""
private String stringV;
@Value("${populate.string:null}")  // 默認(rèn)值是null
private String stringV2;
@Value("${populate.string:defaultValue}")  // 默認(rèn)值是"defaultValue"
private String stringV3;
//注入Array
@Value("${populate.array:}") // 默認(rèn)值是[]
private String[] array;
//注入List
@Value("${populate.list:}")  // 默認(rèn)值是空List,[]
private List<String> list0;
@Value("#{'${populate.list:}'.split(',')}") // 默認(rèn)值是包含一個(gè)空字符串的List [""]
private List<String> list1;
@Value("${populate.list:l1,l2,l3}")  // 默認(rèn)值是[l1,l2,l3]
private List<String> list2;
@Value("#{'${populate.list:l1,l2,l3}'.split(',')}") // 默認(rèn)值是[l1,l2,l3]
private List<String> list3;
@Value("#{'${populate.list:,}'.split(',')}") // 默認(rèn)值是空List,[]
private List<String> list4;
//注入Map
@Value("#{${populate.map:{}}}")    // 默認(rèn)值是null
private Map<String,String> map;
@Value("#{${populate.map:null}}}")  // 默認(rèn)值是null
private Map<String, String> map2;
@Value("#{${populate.map:{k1:'v1',k2:'v2'}}}")  // 默認(rèn)值是{"k1":"v1","k2":"v2"}
private Map<String, String> map3;
@Value("#{${populate.mapList:{}}}")    // 值為{"key1":["v11","v12"],"key2":["v21","v22"],"key3":["v31","v32"]}
private Map<String,List<String>> mapList; 

3、自定義文件注入

在resource目錄下新建petshop/petshop.properties文件,將application.yml中的屬性轉(zhuǎn)換為properties中的key-value格式,也可以是xxx.ini等

## 自定義屬性
my-property:
  name: shawn
  introduce: 我的自定義屬性
  age:
    - 18
    - 19
  shopInfo:
    phone: 36xx102
    address: xx省xx市
    licences: 上市許可證
  pets:
    - pet:
      name: 金毛
      price: 3365.21
    - pet:
      name: 巴哥
      price: 2136.10

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

相關(guān)文章

  • SpringBoot中的統(tǒng)一異常處理詳細(xì)解析

    SpringBoot中的統(tǒng)一異常處理詳細(xì)解析

    這篇文章主要介紹了SpringBoot中的統(tǒng)一異常處理詳細(xì)解析,該注解可以把異常處理器應(yīng)用到所有控制器,而不是單個(gè)控制器,借助該注解,我們可以實(shí)現(xiàn):在獨(dú)立的某個(gè)地方,比如單獨(dú)一個(gè)類,定義一套對(duì)各種異常的處理機(jī)制,需要的朋友可以參考下
    2024-01-01
  • Spring Validator從零掌握對(duì)象校驗(yàn)的詳細(xì)過程

    Spring Validator從零掌握對(duì)象校驗(yàn)的詳細(xì)過程

    SpringValidator學(xué)習(xí)指南從零掌握對(duì)象校驗(yàn),涵蓋Validator接口、嵌套對(duì)象處理、錯(cuò)誤代碼解析等核心概念,幫助開發(fā)者實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)的規(guī)范與高效,本文詳細(xì)介紹Spring Validator從零掌握對(duì)象校驗(yàn),感興趣的朋友一起看看吧
    2025-02-02
  • java 實(shí)現(xiàn)發(fā)短信功能---騰訊云短信

    java 實(shí)現(xiàn)發(fā)短信功能---騰訊云短信

    如今發(fā)短信功能已經(jīng)成為互聯(lián)網(wǎng)公司的標(biāo)配,接下來通過本文給大家介紹java 實(shí)現(xiàn)發(fā)短信功能---騰訊云短信 ,需要的朋友可以參考下
    2019-08-08
  • Maven打包SpringBoot工程的實(shí)現(xiàn)示例

    Maven打包SpringBoot工程的實(shí)現(xiàn)示例

    在使用Spring Boot和Maven的項(xiàng)目中,你可以使用Maven來打包你的項(xiàng)目,本文主要介紹了Maven打包SpringBoot工程的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-05-05
  • Mybatis-Plus使用p6spy對(duì)SQL性能進(jìn)行監(jiān)控的方法

    Mybatis-Plus使用p6spy對(duì)SQL性能進(jìn)行監(jiān)控的方法

    這篇文章主要介紹了Mybatis-Plus使用p6spy對(duì)SQL性能進(jìn)行監(jiān)控的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • Mybatis一對(duì)多關(guān)聯(lián)關(guān)系映射實(shí)現(xiàn)過程解析

    Mybatis一對(duì)多關(guān)聯(lián)關(guān)系映射實(shí)現(xiàn)過程解析

    這篇文章主要介紹了Mybatis一對(duì)多關(guān)聯(lián)關(guān)系映射實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • Spring Boot優(yōu)雅地處理404異常問題

    Spring Boot優(yōu)雅地處理404異常問題

    這篇文章主要介紹了Spring Boot優(yōu)雅地處理404異常問題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • Maven打包時(shí)如何指定啟動(dòng)類

    Maven打包時(shí)如何指定啟動(dòng)類

    這篇文章主要介紹了Maven打包時(shí)如何指定啟動(dòng)類問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • Java接收text/event-stream格式數(shù)據(jù)的詳細(xì)代碼

    Java接收text/event-stream格式數(shù)據(jù)的詳細(xì)代碼

    這篇文章主要介紹了java接收text/event-stream格式數(shù)據(jù),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-07-07
  • Gradle jvm插件系列教程之Java?Library插件權(quán)威詳解

    Gradle jvm插件系列教程之Java?Library插件權(quán)威詳解

    這篇文章主要介紹了Java?Library插件權(quán)威詳解,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2024-01-01

最新評(píng)論