SpringBoot配置数据源

SpringBoot配置数据源

数据源使用的是阿里的Driud。

1.配置之前 先看一下xml的配置。

-------------------spring-mybatis.xml文件--------------------------




    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    



    
    
    
     


    
    

-------------------mybatis-interceptor.xml文件------------------------------
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
"http://mybatis.org/dtd/mybatis-3-config.dtd">  
  
  
  
      
      
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
          
      
  
 

这里面可以看到配置了DruidDataSource、SqlSessionFactoryBean、MapperScannerConfigurer三个bean,其中DruidDataSource配置了最基本的链接属性;SqlSessionFactoryBean配置数据源、mapper.xml路径和PageHelper插件填充;MapperScannerConfigurer设置的自动扫描的基本包basePackage跟sqlSessionFactory。
对应的在springBoot中,我们如果不用xml配置,则可以用@Configuration、@bean来进行注解配置。
@Configuration注解,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean。

2.看springBoot配置,首先配置DruidDataSource,创建一个DruidDBConfig类,表注@Configuration。代码如下:

@Configuration  
public class DruidDBConfig {  
    private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);   
    @Value("${spring.datasource.url}")  
    private String dbUrl;   
    @Value("${spring.datasource.username}")  
    private String username;  
    @Value("${spring.datasource.password}")  
    private String password;  
    @Value("${spring.datasource.driverClassName}")  
    private String driverClassName;  
    @Value("${spring.datasource.initialSize}")  
    private int initialSize;   
    @Value("${spring.datasource.minIdle}")  
    private int minIdle;  
    @Value("${spring.datasource.maxActive}")  
    private int maxActive;  
    @Value("${spring.datasource.maxWait}")  
    private int maxWait;  
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")  
    private int timeBetweenEvictionRunsMillis;  
    @Value("${spring.datasource.minEvictableIdleTimeMillis}")  
    private int minEvictableIdleTimeMillis;  
    @Value("${spring.datasource.validationQuery}")  
    private String validationQuery;   
    @Value("${spring.datasource.testWhileIdle}")  
    private boolean testWhileIdle;  
    @Value("${spring.datasource.testOnBorrow}")  
    private boolean testOnBorrow;  
    @Value("${spring.datasource.testOnReturn}")  
    private boolean testOnReturn;  
    @Value("${spring.datasource.poolPreparedStatements}")  
    private boolean poolPreparedStatements;   
    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")  
    private int maxPoolPreparedStatementPerConnectionSize;  
    @Value("${spring.datasource.filters}")  
    private String filters;    
    @Value("{spring.datasource.connectionProperties}")  
    private String connectionProperties;   
    @Bean(value="dataSource")     //声明其为Bean实例  
    @Primary  //在同样的DataSource中,首先使用被标注的DataSource  
    public DataSource dataSource(){  
        DruidDataSource datasource = new DruidDataSource();  
        datasource.setUrl(this.dbUrl);  
        datasource.setUsername(username);  
        datasource.setPassword(password);  
        datasource.setDriverClassName(driverClassName);  
        //configuration  
        datasource.setInitialSize(initialSize);  
        datasource.setMinIdle(minIdle);  
        datasource.setMaxActive(maxActive);  
        datasource.setMaxWait(maxWait);  
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
        datasource.setValidationQuery(validationQuery);  
        datasource.setTestWhileIdle(testWhileIdle);  
        datasource.setTestOnBorrow(testOnBorrow);  
        datasource.setTestOnReturn(testOnReturn);  
        datasource.setPoolPreparedStatements(poolPreparedStatements);  
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);  
        try {  
            datasource.setFilters(filters);  
        } catch (SQLException e) {  
            logger.error("druid configuration initialization filter", e);  
        }  
        datasource.setConnectionProperties(connectionProperties);  
        return datasource;  
    }  
}

至此,DruidDataSource数据源在系统运行的时候,会自动创建一个bean。

3.若想使用Druid的监控,则需要额外配置StatViewServlet 和 filterRegistrationBean,这里单独拎出来便于理解,此处配置也可以放置在DruidDBConfig类中。

@Configuration
public class DruidConfiguration { 
   /**
    * 注册一个StatViewServlet
    * @return
    */
   @Bean
   public ServletRegistrationBean DruidStatViewServle2(){
          //org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
          ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
          //添加初始化参数:initParams
          //白名单:
          servletRegistrationBean.addInitParameter("allow","127.0.0.1");
          //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
          servletRegistrationBean.addInitParameter("deny","192.168.1.73");
          //登录查看信息的账号密码.
          servletRegistrationBean.addInitParameter("loginUsername","admin2");
          servletRegistrationBean.addInitParameter("loginPassword","123456");
          //是否能够重置数据.
          servletRegistrationBean.addInitParameter("resetEnable","false");
          return servletRegistrationBean;
   }   
   /**
    * 注册一个:filterRegistrationBean
    * @return
    */
   @Bean
   public FilterRegistrationBean druidStatFilter2(){       
          FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
          //添加过滤规则.
          filterRegistrationBean.addUrlPatterns("/*");
          //添加不需要忽略的格式信息.
          filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid2/*");
          return filterRegistrationBean;
   } 
 }

这里的配置类同等于xml配置文件:


DruidWebStatFilter
com.alibaba.druid.support.http.WebStatFilter

    exclusions
    *.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*



    DruidWebStatFilter
    /*


    DruidStatView
    com.alibaba.druid.support.http.StatViewServlet


    DruidStatView
    /druid/*

同样的还有另外一种方式:

1)创建DruidStatFilter。

@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",  
initParams={  
    @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源  
}  
)  
public class DruidStatFilter extends WebStatFilter {
}

2)创建DruidStatViewServlet。

@WebServlet(urlPatterns="/druid/*",  
initParams={  
     @WebInitParam(name="allow",value="127.0.0.1,192.168.163.1"),// IP白名单(没有配置或者为空,则允许所有访问)  
     @WebInitParam(name="deny",value="192.168.1.73"),// IP黑名单 (存在共同时,deny优先于allow)  
     @WebInitParam(name="loginUsername",value="admin"),// 用户名  
     @WebInitParam(name="loginPassword",value="123456"),// 密码  
     @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能  
})  
public class DruidStatViewServlet extends StatViewServlet {  
    private static final long serialVersionUID = -2688872071445249539L; 
}

4.配置sqlSessionFactory,此bean是SqlSessionFactoryBean类型。

@Configuration
public class MyBatisConfig implements TransactionManagementConfigurer{
    private Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);
    //@Autowired 
    //private DruidDataSource dataSource;
    @Value("${spring.datasource.type}")  
    private Class dataSourceType;  
    @Bean(name="dataSource", destroyMethod = "close", initMethod="init")  
    @ConfigurationProperties(prefix = "spring.datasource")  
    public DataSource dataSource() {
        return DataSourceBuilder.create().type(dataSourceType).build();  
    }  
    @Bean(name = "sqlSessionFactory")//3
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource());
        //bean.setTypeAliasesPackage("com.hjf.boot.demo.boot_mybatis.domain");
        //分页插件 //4
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        //添加插件
        bean.setPlugins(new Interceptor[]{pageHelper});
        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setMapperLocations(resolver.getResources("classpath:/mybatis/*Mapper.xml"));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    @Bean
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}

5.配置MapperScannerConfigurer,设置自动扫描。

@Configuration
@AutoConfigureAfter(MyBatisConfig.class)//见文思意,在MyBatisConfig配置之后加载
public class MyBatisMapperScannerConfig {
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        //对应
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        //对应
        mapperScannerConfigurer.setBasePackage("com.lcl.springBoot.dao");
        return mapperScannerConfigurer;
    }
}

至此配置完毕,对于资源文件在resources目录下:

 resources
   --application.properties//存放资源文件
   --mybatis//文件夹存放mapper文件
       --DemoMapper.xml //本人用的测试mapper

application.properties文件内容(千篇一律,满大街都是= =!):

##DATASOURCE(DataSourceAutoConfiguration&DataSourceProperties)
# 驱动配置信息   
spring.datasource.url = jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username= root
spring.datasource.password=
spring.datasource.driverClassName=com.mysql.jdbc.Driver 
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource 
##连接池属性配置
spring.datasource.initialSize=5  
spring.datasource.minIdle=5  
spring.datasource.maxActive=20  
spring.datasource.maxWait=60000  
spring.datasource.timeBetweenEvictionRunsMillis=60000  
spring.datasource.minEvictableIdleTimeMillis=300000  
spring.datasource.validationQuery=SELECT 1 FROM DUAL  
spring.datasource.testWhileIdle=true  
spring.datasource.testOnBorrow=false  
spring.datasource.testOnReturn=false  
spring.datasource.poolPreparedStatements=true  
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20  
spring.datasource.filters=stat,wall,log4j  
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000  

结尾:在MyBatisConfig中关于DruidDataSource,一开始使用的形式是:

    @Autowired 
    private DruidDataSource dataSource;

此时发现不能自动实例化bean,而后改为一下形式解决,没有看源码不知何故,以后有时间在看源码进行分析:

    @Value("${spring.datasource.type}")  
    private Class dataSourceType;  
    @Bean(name="dataSource", destroyMethod = "close", initMethod="init")  
    @ConfigurationProperties(prefix = "spring.datasource")  
    public DataSource dataSource() {
        return DataSourceBuilder.create().type(dataSourceType).build();  
    }  

你可能感兴趣的:(SpringBoot,Driud)