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

Spring運(yùn)行時(shí)手動(dòng)注入bean的方法實(shí)例

 更新時(shí)間:2022年05月31日 10:21:14   作者:xiuyuandashen  
spring給我們提供了IOC服務(wù),讓我們可以用注解的方式,方便的使用bean的相互引用,下面這篇文章主要給大家介紹了關(guān)于Spring運(yùn)行時(shí)手動(dòng)注入bean的相關(guān)資料,需要的朋友可以參考下

有時(shí)候,會(huì)有這樣一個(gè)需求,在程序運(yùn)行時(shí)動(dòng)態(tài)生成的對象,需要注入到Spring容器中進(jìn)行管理。

下面是獲取Bean以及注入Bean的工具類

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Map;

@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    public static Object getBean(Class name) throws BeansException {
        return applicationContext.getBean(name);
    }

    /**
     * bean注入spring容器
     * map[id,className,...]
     * id 為 bean的標(biāo)識(shí)
     * className 為 類的全限定類名
     * ... 為其他屬性
     * @param map
     */
    public static void injectBean(Map<String, String> map) {
        String className = map.get("className");
        Class<?> aClass;
        if (className == null) {
            throw new RuntimeException("map參數(shù)缺少className");
        }

        try {
            aClass = Class.forName(className);
            if (aClass == null) {
                throw new RuntimeException("className不存在");
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(aClass);
        Field[] declaredFields = aClass.getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            String fieldName = declaredFields[i].getName();
            if (map.get(fieldName) != null) {
                // 必須設(shè)置可訪問,否則下面的操作做不了
                // declaredFields[i].setAccessible(true);
                builder.addPropertyValue(fieldName, map.get(fieldName));
            }
        }
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext;
        // 注冊bean 第一個(gè)參數(shù)為 name ,第二個(gè)為 bean定義類
        String id = map.get("id");
        if (id == null) {
            registry.registerBeanDefinition(className, builder.getBeanDefinition());
            return;
        }
        registry.registerBeanDefinition(id, builder.getBeanDefinition());
    }
}

測試

@Test
   public void test2() {
      HashMap<String, String> map = new HashMap<>();
      map.put("id", "helloTask");
      map.put("className", "com.example.demo.Task.HelloTask4");
      // 注冊bean
      SpringUtils.injectBean(map);
//    HelloTask4 helloTask =(HelloTask4) SpringUtils.getBean(HelloTask4.class);
      HelloTask4 helloTask = (HelloTask4) SpringUtils.getBean("helloTask");
      System.out.println(helloTask.getClass());
   }

附:利用注解向Spring容器中注入Bean

常用注解包含:@Controller、@Service、@Repository、@Component,其中@Controller、@Service、@Repository都是基于@Component的擴(kuò)展。通常的@Controller用于標(biāo)識(shí)處理前端請求的類,@Service用于標(biāo)識(shí)業(yè)務(wù)邏輯類,@Repository用于標(biāo)識(shí)DAO層的類,@Component為通用注解,可以標(biāo)注在任何想要注入容器中的類上面;

@Component
//@Controller
//@Service
//@Repository
class Stu{
    
}

也可以利用@Bean與@Configuration注入,其中@Configuration用于標(biāo)注一個(gè)配置類,@Bean用于標(biāo)注返回需注入Bean的方法;

@Configuration
class MyConfig{
    @Bean
    public Student getStudent(){
        return new Student();
    }
}

總結(jié)

到此這篇關(guān)于Spring運(yùn)行時(shí)手動(dòng)注入bean的文章就介紹到這了,更多相關(guān)Spring運(yùn)行手動(dòng)注入bean內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java基礎(chǔ)之容器Vector詳解

    Java基礎(chǔ)之容器Vector詳解

    這篇文章主要介紹了Java基礎(chǔ)之容器Vector詳解,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有很好的幫助,需要的朋友可以參考下
    2021-04-04
  • Java中的ThreadLocalMap源碼解讀

    Java中的ThreadLocalMap源碼解讀

    這篇文章主要介紹了Java中的ThreadLocalMap源碼解讀,ThreadLocalMap是ThreadLocal的內(nèi)部類,是一個(gè)key-value數(shù)據(jù)形式結(jié)構(gòu),也是ThreadLocal的核心,需要的朋友可以參考下
    2023-09-09
  • 一文深入解析JDBC超時(shí)機(jī)制

    一文深入解析JDBC超時(shí)機(jī)制

    恰當(dāng)?shù)腏DBC超時(shí)設(shè)置能夠有效地減少服務(wù)失效的時(shí)間,下面這篇文章主要給大家介紹了關(guān)于JDBC超時(shí)機(jī)制的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2021-10-10
  • eclipse輸出Hello World的實(shí)現(xiàn)方法

    eclipse輸出Hello World的實(shí)現(xiàn)方法

    這篇文章主要介紹了eclipse輸出Hello World的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • Java上傳文件到服務(wù)器端的方法

    Java上傳文件到服務(wù)器端的方法

    這篇文章主要為大家詳細(xì)介紹了Java上傳文件到服務(wù)器端的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • JAVA中的OutputStreamWriter流解析

    JAVA中的OutputStreamWriter流解析

    這篇文章主要介紹了JAVA中的OutputStreamWriter流解析,OutputStreamWriter提供了一種方便的方式將字符數(shù)據(jù)寫入到輸出流中,并進(jìn)行字符編碼轉(zhuǎn)換,它是Java中處理字符流和字節(jié)流之間轉(zhuǎn)換的重要工具之一,需要的朋友可以參考下
    2023-10-10
  • springboot?html調(diào)用js無效400問題及解決

    springboot?html調(diào)用js無效400問題及解決

    這篇文章主要介紹了springboot?html調(diào)用js無效400的問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • eclipse項(xiàng)目在IDEA中打開并運(yùn)行的詳細(xì)圖文教程

    eclipse項(xiàng)目在IDEA中打開并運(yùn)行的詳細(xì)圖文教程

    這篇文章主要給大家介紹了關(guān)于eclipse項(xiàng)目在IDEA中打開并運(yùn)行的詳細(xì)圖文教程,至從使用IDEA開發(fā)工具以來,不少次有使用IDEA運(yùn)行Eclipse項(xiàng)目或非Maven項(xiàng)目,所以這里給大家總結(jié)下,需要的朋友可以參考下
    2023-09-09
  • SpringBoot讀取資源目錄中JSON文件的方法實(shí)例

    SpringBoot讀取資源目錄中JSON文件的方法實(shí)例

    最近做項(xiàng)目遇到需要將json類型的配置文件引用到項(xiàng)目中,已經(jīng)將讀取json文件的方法封裝成工具類,下面這篇文章主要給大家介紹了關(guān)于SpringBoot讀取資源目錄中JSON文件的相關(guān)資料,需要的朋友可以參考下
    2023-04-04
  • IntelliJ IDEA創(chuàng)建maven web項(xiàng)目的圖文步驟(IDEA新手適用)

    IntelliJ IDEA創(chuàng)建maven web項(xiàng)目的圖文步驟(IDEA新手適用)

    這篇文章主要介紹了IntelliJ IDEA創(chuàng)建maven web項(xiàng)目的圖文步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03

最新評(píng)論