当前位置:Gxlcms > 数据库问题 > jdbcTemplate 基本配置

jdbcTemplate 基本配置

时间:2021-07-01 10:21:17 帮助过:8人阅读

public class VideoSecuriteDaoImpl { @Autowired private JdbcTemplate jdbcTemplate; private static final Logger log = LoggerFactory.getLogger(VideoSecuriteDaoImpl.class); public List<Map<String,Object>> getSecuriteMap(int pageSize, int pageNo) { List<Map<String,Object>> list = new ArrayList<>(); if (pageSize != 0) { String sql = "select camillo,encode from video_securities where is_use = 0 limit " + (pageNo - 1) * pageSize + "," + pageSize; try { list = jdbcTemplate.queryForList(sql); } catch (DataAccessException e) { log.error("查询VideoSecurite中camillo,encode报错: " + e.toString()); } } return list; } }

这里实现了一个分页查询,App.java的任务是选择profile,加载配置文件,以及简单测试dao查询的内容:

package com.changjiang.test.jdbcTemplate;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.changjiang.test.jdbcTemplate.dao.VideoSecuriteDaoImpl;

/**
 * Hello world!
 *
 */
public class App {
    private static Logger logger = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        System.setProperty("spring.profiles.active", "production");
        logger.info("===========================================================================");
        logger.info("                     服务将在[{}]环境启动                  ", "production");
        logger.info("===========================================================================");
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });
        ac.start();
        VideoSecuriteDaoImpl videoSecuriteDaoImpl = ac.getBean(VideoSecuriteDaoImpl.class);
        List<Map<String, Object>> list = videoSecuriteDaoImpl.getSecuriteMap(1000, 1);
        for (Map<String, Object> map : list) {
            System.out.println(map.get("camillo"));
        }
        ac.close();
    }
}

在applicationContext.xml中只定义了一个profile,即production,实际开发中可以根据开发,测试和发布的需要配置不同的profile,切换时只需要改一个jar文件的输入参数即可,看看该文件的配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p" xmlns="http://www.springframework.org/schema/beans"
    xmlns:c="http://www.springframework.org/schema/c" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd"
    default-lazy-init="true">

    <description>Spring公共配置</description>

    <!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean 进行注入 -->
    <context:annotation-config />

    <!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
    <context:component-scan base-package="com.changjiang.test.jdbcTemplate" />
    <!-- spring-jdbc -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 使用annotation定义事务 -->
    <tx:annotation-driven proxy-target-class="true" />
    <bean id="transactionManager" name="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
    </bean>
    <!-- 定义事务规则 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
        </tx:attributes>
    </tx:advice>
    <!-- 声明事务 -->
    <aop:config proxy-target-class="true">
        <aop:pointcut id="transactionPointcut"
            expression="execution(* com.changjiang.test.jdbcTemplate.*.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut"
            advice-ref="transactionAdvice" />
    </aop:config>

    <!-- production环境 -->
    <beans profile="production">
        <context:property-placeholder
            ignore-unresolvable="true" location="classpath*:/application.properties" />
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
            init-method="init" destroy-method="close">
            <property name="driverClassName" value="${jdbc.driver}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
            <!-- 初始化连接大小 -->
            <property name="initialSize" value="5" />
            <property name="maxActive">
                <value>${jdbc.pool.maxActive}</value>
            </property>
            <property name="minIdle">
                <value>${jdbc.pool.minIdle}</value>
            </property>
            <property name="maxWait">
                <value>${jdbc.pool.maxWait}</value>
            </property>
            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000" />
            <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            <property name="minEvictableIdleTimeMillis" value="300000" />
            <!-- 打开removeAbandoned功能 -->
            <property name="removeAbandoned" value="true" />
            <!-- 1800秒,也就是30分钟 -->
            <property name="removeAbandonedTimeout" value="1800" />
            <!-- 关闭abanded连接时输出错误日志 -->
            <property name="logAbandoned" value="true" />
            <property name="timeBetweenLogStatsMillis" value="300000" />
            <!-- 加密 -->
            <property name="connectionProperties" value="config.decrypt=true" />
            <property name="proxyFilters">
                <list>
                    <ref bean="logFilter" />
                </list>
            </property>
            <property name="filters" value="stat,config,wall,slf4j,log4j" />
        </bean>
        <bean id="logFilter" class="com.alibaba.druid.filter.logging.Log4jFilter">
            <property name="statementExecutableSqlLogEnable" value="false" />

            <property name="statementLoggerName" value="sqlLogger" />
            <!--<property name="resultSetLogEnabled" value="false" /> -->
        </bean>
    </beans>
</beans>

  在该配置中有许多点,可以作为专门的小节来分析,在这里,需要注意的是,在所有的数据加载进spring容器之前,需要激活对应的剖面--profile,App.java中提供了一种方式,它会先将production激活,并在指定的位置找到各个属性对应的值,再将bean加载到spring容器之中,否则会出现org.springframework.beans.factory.NoSuchBeanDefinitionException。这是在Spring3.1之后新增加的功能,关于它的详细用法,看下一篇Spring之Environment。

 

jdbcTemplate 基本配置

标签:

人气教程排行