自动注入bean,简化持久化

import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;

import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Component
public class DataSourceRegistrar implements BeanDefinitionRegistryPostProcessor, ResourceLoaderAware {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceRegistrar.class);

    private static final String DATABASE_PROPERTIES_FILE = "database.properties";

    private ResourceLoader resourceLoader;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        Properties databases = this.loadConfigProperties();
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(BasicDataSource.class);
        for (String prop : databases.stringPropertyNames()) {
            String key = prop;
            String value = databases.getProperty(prop);
            beanDefinitionBuilder.addPropertyValue(key,value);
        }
        BeanDefinition dataSourceDef =  beanDefinitionBuilder.getBeanDefinition();
        registry.registerBeanDefinition("dataSource",dataSourceDef);
        //<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        //<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        //<property name="url" value="jdbc:mysql://..."/>
        //<property name="username" value="..."/>
        //<property name="password" value="..."/>
        //</bean>

        String sqlSessionFactoryBean = SqlSessionFactoryBean.class.getSimpleName();
        BeanDefinition sqlSessionFactoryBeanDef = BeanDefinitionBuilder.rootBeanDefinition(SqlSessionFactoryBean.class)
                .addPropertyReference("dataSource","dataSource")
                .getBeanDefinition();
        registry.registerBeanDefinition(sqlSessionFactoryBean,sqlSessionFactoryBeanDef);
        //<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        //<property name="dataSource" ref="dataSource"/>
        //</bean>

        String mapperScannerConfigurer = MapperScannerConfigurer.class.getSimpleName();
        BeanDefinition mapperScannerConfigurerBeanDef =
                BeanDefinitionBuilder.rootBeanDefinition(MapperScannerConfigurer.class)
                        .addPropertyValue("basePackage", "hw.test.db.dao")
                        .getBeanDefinition();
        registry.registerBeanDefinition(mapperScannerConfigurer,mapperScannerConfigurerBeanDef);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    private Properties loadConfigProperties() {
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            Resource resource = this.resourceLoader.getResource(DATABASE_PROPERTIES_FILE);
            if (resource.exists()) {
                inputStream = resource.getInputStream();
                properties.load(inputStream);
            } else {
                logger.warn(DATABASE_PROPERTIES_FILE + " not found");
            }
        } catch (IOException e) {
            throw new FatalBeanException("Load " + DATABASE_PROPERTIES_FILE + " failed");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("Close inputStream failed", e);
                }
            }
        }
        logger.info("{}:{}", DATABASE_PROPERTIES_FILE, properties);
        return properties;
    }

}

  以为代码自动编写bean的注入,不需要再写xml配置文件

dao层代码

import org.apache.ibatis.annotations.Select;

public interface PcapFileDao {

    @Select("select * from pcap_file where id=#{id}")
    PcapFile getPcapFile(int id);
}

最后使用

@Autowired
private PcapFileDao pcapFileDao;
posted @ 2017-08-18 16:52  单曲TI  阅读(408)  评论(0编辑  收藏  举报