spring 動態建立bean

spring具體的建立的代碼以下java

一、BeanUtil 的代碼以下spring

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;

/**
 * 管理bean類
 */
public class BeanUtil {

    // Spring Bean 工廠
    public static DefaultListableBeanFactory beanFactory;
    //注意在spring初始化刷新後要調用這個init方法來得到新的beanFactory對象
    public static void init(ApplicationContext applicationContext) {
        beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
    }
    /**
     * 動態增長bean
     * 
     * @param className
     * @param beanKey
     * @param propertyMap
     * @param referenceMap
     * @return
     */
    public static boolean addBean(
            String className, String beanKey, Map<String, Object> propertyMap,
            Map<String, String> referenceMap, List<Object> propertyConstrList,
            List<String> referenceConstrList, String destroyMethod) {
        // 判斷Spring容器中是否存在該Bean
        if (beanFactory.containsBeanDefinition(className)) {
            return true;
        }

        BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(className);
        bdb.getBeanDefinition().setAttribute("id", beanKey);

        // 設置bean參數屬性
        if (propertyMap != null && !propertyMap.isEmpty()) {
            Iterator<String> propertyKeys = propertyMap.keySet().iterator();
            while (propertyKeys.hasNext()) {
                String keyString = propertyKeys.next();
                bdb.addPropertyValue(keyString, propertyMap.get(keyString));
            }
        }

        // 設置bean參數引用
        if (referenceMap != null && !referenceMap.isEmpty()) {
            Iterator<String> referenceKeys = referenceMap.keySet().iterator();
            while (referenceKeys.hasNext()) {
                String keyString = referenceKeys.next();
                bdb.addPropertyReference(keyString, referenceMap.get(keyString));
            }
        }

        // 設置bean構造參數屬性
        if (propertyConstrList != null && !propertyConstrList.isEmpty()) {
            for (int i = 0; i < propertyConstrList.size(); i++) {
                bdb.addConstructorArgValue(propertyConstrList.get(i));
            }
        }

        // 設置bean構造參數引用
        if (referenceConstrList != null && !referenceConstrList.isEmpty()) {
            for (int i = 0; i < referenceConstrList.size(); i++) {
                bdb.addConstructorArgReference(referenceConstrList.get(i));
            }
        }

        if (destroyMethod != null && !destroyMethod.isEmpty()) {
            bdb.setDestroyMethodName(destroyMethod);
        }

        beanFactory.registerBeanDefinition(beanKey, bdb.getBeanDefinition());

        return true;
    }

    /**
     * 獲取Bean
     * 
     * @param requiredType
     * @return
     */
    public static <T> T getBean(Class<T> requiredType) {
        return beanFactory.getBean(requiredType);
    }

    /**
     * 獲取bean
     * @param beanName
     * @param requiredType
     * @return
     */
    public static <T> T getBean(String beanName,Class<T> requiredType) {
        return  beanFactory.getBean(beanName,requiredType);
    }

}

二、DataSourceUtil 類的代碼以下sql

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import com.test.BaseConfigUtil;


/**
 * 加載數據源類,將${catalina.home}/ybg/conf下面的全部數據源文件加入到bean工廠中
 */
public class DataSourceUtil {

    /**
     * 初始化
     * 
     * @param applicationContext
     */
    public static void init(ApplicationContext applicationContext) {

            File dataDirectory = new File(System.getProperty("catalina.home") + File.separator + "test" + File.separator + "conf");
    // 數據源文件一定要是properties類型。 
    //過濾的文件名稱以db開頭,以properties結尾
        File[] dataFiles = dataDirectory.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                String fileName = name.toLowerCase();

                if (fileName.endsWith(".properties")) {
                    if(fileName.startsWith("db")) {
                        return true;
                    }
                }

                return false;
            }
        });
    try (Reader reader = new InputStreamReader(new FileInputStream(dataFiles[i]), "UTF-8")) {
                Properties properties = new Properties();
                properties.load(reader);//讀取數據庫的.properties配置文件

                if (!properties.isEmpty()) {
                    // 創建數據源的bean
                    Map<String, Object> propertyMap = new HashMap<String, Object>();

                    propertyMap.put("driverClassName",properties.getProperty("sqlDriver"));
                    propertyMap.put("url",properties.getProperty("sqlUrl"));
                    propertyMap.put("username",properties.getProperty("sqlUsername"));
                    propertyMap.put("password", properties.getProperty("sqlPassword"));
                    propertyMap.put("initialSize",properties.getProperty("sqlInitialSize"));
                    propertyMap.put("maxTotal",properties.getProperty("sqlMaxTotal"));
                    propertyMap.put("maxIdle",properties.getProperty("sqlMaxIdle"));
                    propertyMap.put("maxWaitMillis",properties.getProperty("sqlMaxWaitMillis"));

                    BeanUtil.addBean( "org.apache.commons.dbcp2.BasicDataSource", name + "_dataSource", propertyMap, null, null, null, "close");

                    // 創建jdbcTemplate的bean
                    List<String> referenceConstrList = new ArrayList<String>();
                    referenceConstrList.add(name + "_dataSource");

                    BeanUtil.addBean( "org.springframework.jdbc.core.JdbcTemplate", name + "_jdbcTemplate", null, null, null, referenceConstrList, null);
                    LogUtil.info("load datasource file {} success!", dataFiles[i].getAbsolutePath());
                }
            } catch (Exception e) {
                LogUtil.error("load datasource file {} fail!", dataFiles[i].getAbsolutePath());
            }
        }
}

    /**
     * 獲取數據源

     * @param datasourceFileName 數據源配置文件名
     * @return
     */
    public static JdbcTemplate getJdbcTemplate(String datasourceFileName) {
        String id = datasourceFileName + "_jdbcTemplate";
        return BeanUtil.getBean(id, JdbcTemplate.class);
    }
}

動態建立bean的代碼位置以下圖 
動態建立bean的示意圖數據庫

三、類好比下用xml加載dataSource和jdbcTemplate的方法apache

<!-- 數據源配置 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${sqlDriver}" />
        <property name="url"             value="${sqlUrl}" />
        <property name="username"        value="${sqlUsername}" />
        <property name="password"        value="${sqlPassword}" />
        <property name="initialSize"     value="${sqlInitialSize}"/>  
        <!-- 鏈接池啓動時建立的鏈接數 -->
        <!-- 鏈接池最大鏈接數 -->
        <property name="maxIdle"         value="${sqlMaxIdle}"/>     
         <!-- 鏈接池最大空閒鏈接數。推薦與 maxTotal 的值一致。 -->
        <!-- 等待獲取鏈接的時間.毫秒 -->
    </bean> 
    <!-- 配置Spring對數據庫事務的支持   -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" c:dataSource-ref="dataSource"/>
    <!-- 開啓註解事務的支持 -->
    <tx:annotation-driven transaction-manager="txManager"/>

    <!-- 配置Template -->
    <bean id="Template" class="org.springframework.jdbc.core.JdbcTemplate" c:dataSource-ref="dataSou
相關文章
相關標籤/搜索