Spring整合配置Mybatis
1.配置数据源(连接数据库最基本的属性配置,如数据库url,账号,密码,和数据库驱动等最基本参数配置)
<!-- 导入properties配置文件 --> <context:property-placeholder location="classpath*:properties/jdbc.properties"/> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:properties/jdbc.properties"/> </bean> <!--1 数据源基本配置 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="url" value="${jdbc.url}"/> <property name="driverClassName" value="${jdbc.driverClassName}"/> </bean> <!—2 数据源基本配置--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="driverClassName" value="${jdbc.driver}" /> <property name="maxActive" value="${jdbc.maxActive}}" /> <property name="minIdle" value="${minldle}" /> </bean>
数据库参数配置统一写入jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver #数据库地址 jdbc.url=jdbc:mysql://localhost:3306/personal_test?useUnicode=true&characterEncoding=utf8 #用户名 jdbc.username=root #密码 jdbc.password=123456 #最大连接数 maxPoolSize=30 #最小连接数 minPoolSize=10 #关闭连接后不自动commit autoCommitOnClose=false #获取连接超时时间 checkoutTimeout=10000 #当获取连接失败重试次数 acquireIncrement=2
2.配置SessionFactory(用于将数据源和mybatis的mapper映射文件进行管理和初始化)
<!-- 创建sessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 扫描mapper映射文件 --> <property name="mapperLocations" value="classpath*:mapping/*.xml" /> </bean>
3.扫描mapper映射文件所对应的dao接口类(其实dao接口的是实现类就是mapper.xml映射文件,此配置是为了将接口和映射文件进行初始化)
<!-- 扫描与mapper映射文件对应的dao接口类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value=" com.zsm.godsoftware.dao "/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>
4.创建事务(事务有两种配置方式:注解方式和aop切入方式)
<!-- 创建事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean>
4.1注解方式
<!-- 注解式事务配置,启动事务注解驱动 -->
<tx:annotation-driven/>
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
4.2 AOP织入方式
<!-- 开启注解扫描 --> <context:component-scan base-package="com.cjh.aop2"/> <!-- 开启aop注解方式,此步骤s不能少,这样java类中的aop注解才会生效 --> <aop:aspectj-autoproxy/> <!-- 目标对象 --> <bean id="knight" class="com.cjh.aop2.BraveKnight"/> <!-- 切面bean --> <bean id="mistrel" class="com.cjh.aop2.Minstrel"/> <!-- 面向切面编程 --> <aop:config> <aop:aspect ref="mistrel"> <!-- 定义切点 --> <aop:pointcut expression="execution(* *.saying(..))" id="embark"/> <!-- 声明前置通知 (在切点方法被执行前调用)--> <aop:before method="beforSay" pointcut-ref="embark"/> <!-- 声明后置通知 (在切点方法被执行后调用)--> <aop:after method="afterSay" pointcut-ref="embark"/> </aop:aspect> </aop:config> <!-- aop切入式事务配置 --> <tx:advice id="trAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="serviceAdvice" expression="execution(* service.serviceImpl.*.*(..))"/> <aop:advisor advice-ref="trAdvice" pointcut-ref="serviceAdvice"/> </aop:config> <aop:config> <!-- 两个切面--> <aop:aspect ref="company"> <!-- 利用切面为特定的类添加新功能 --> <aop:declare-parents types-matching="com.springAop.InstanceMine+" <!-- 实现了InstanceMine接口的实现类可以强转成InstanceOtheer类型的对象并使用他的实现类的方法的方法 --> implement-interface="com.springAop.InstanceOther" default-impl="com.springAop.OtherImpl"/>
<!--InstanceOther的默认实现类,当InstanceMine对象强转成InstanceOther的对象时,默认实现类为OtherImpl--> </aop:aspect> </aop:config>
最终配置:
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ @(#) applicationContext.xml ~ <br> Copyright: Copyright (c) 2017 ~ <br> @author cjh ~ <br> 2017-10-29 15:45:16 --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <!-- 导入properties配置文件 --> <context:property-placeholder location="classpath*:/jdbc.properties"/> <!-- 扫描注解包 --> <context:component-scan base-package="dao.daoInterface"/> <context:component-scan base-package="service.serviceImpl" /> <!-- 数据源基本配置 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="url" value="${jdbc.url}"/> <property name="driverClassName" value="${jdbc.driverClassName}"/> </bean> <!-- 创建sessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 扫描mapper映射文件 --> <property name="mapperLocations" value="classpath*:dao/mapping/*.xml" /> </bean> <!-- 扫描与mapper映射文件对应的dao接口类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="dao.daoInterface"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- 创建事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 注解式事务配置,启动事务注解驱动 --> <!--<tx:annotation-driven/>--> <!-- aop切入式事务配置 --> <tx:advice id="trAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="serviceAdvice" expression="execution(* service.serviceImpl.*.*(..))"/> <aop:advisor advice-ref="trAdvice" pointcut-ref="serviceAdvice"/> </aop:config> </beans>
二、Spring整合配置Hibernate
Hibernate与MyBatis配置大同小异,需单独配置SessionFactory(因为Hibernate对数据库操作做了封装,所以需要一些额外的属性配置)
<!-- 创建sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <!--<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>--> </props> </property> <!-- 实体类映射文件 --> <property name="mappingLocations"> <list> <value>classpath*:/domain/*.hbm.xml</value> </list> </property> <!-- 扫描实体类包 --> <property name="packagesToScan"> <value>domain</value> </property> <!-- 实体类 --> <property name="annotatedClasses"> <list> <value>domain.UserEntity</value> </list> </property> </bean>
最终配置如下:
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ @(#) applicationContext.xml ~ <br> Copyright: Copyright (c) 2017 ~ <br> @author cjh ~ <br> 2017-10-29 15:45:16 --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 导入properties配置文件 --> <context:property-placeholder location="classpath*:/jdbc.properties"/> <!-- 扫描注解包 --> <context:component-scan base-package="dao.daoImpl"/> <context:component-scan base-package="service.serviceImpl" /> <!-- 数据源基本配置 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="url" value="${jdbc.url}"/> <property name="driverClassName" value="${jdbc.driverClassName}"/> </bean> <!-- 创建sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <!--<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>--> </props> </property> <!-- 实体类映射文件 --> <property name="mappingLocations"> <list> <value>classpath*:/domain/*.hbm.xml</value> </list> </property> <!-- 扫描实体类包 --> <property name="packagesToScan"> <value>domain</value> </property> <!-- 实体类 --> <property name="annotatedClasses"> <list> <value>domain.UserEntity</value> </list> </property> </bean> <!-- 创建声明式事务管理 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 事务通知(注解方式) --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 事务通知(aop方式) --> <!--<tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!– propagation配置传播行为,isolation配置隔离方式 –> <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED" /> </tx:attributes> </tx:advice> <!– aop织入通知 –> <aop:config> <aop:pointcut id="serviceOption" expression="(execution(* service.serviceImpl.*.*(..)) and (execution(* dao.daoImpl.*.*(..))))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOption"/> </aop:config>--> </beans>
三、配置HandlerMapping、HandlerAdapter
<!--配置HandlerMapping、HandlerAdapter--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
配置pom.xml打包加入资源文件:
<!-- 资源文件 --> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.js</include> </includes> <filtering>true</filtering> </resource> </resources>
四、Logback配置
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- 控制台输出 --> <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern> </encoder> </appender> <!-- 时间滚动输出 level为 DEBUG 日志 --> <appender name="file—debug" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>DEBUG</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY </onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>D:/logs/debug.%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder> <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern> </encoder> </appender> <!-- 时间滚动输出 level为 ERROR 日志 --> <appender name="file—error" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY </onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>D:/logs/error.%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder> <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern> </encoder> </appender> <!-- 特定过滤含有某字符串的日志 --> <appender name="file-str" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.core.filter.EvaluatorFilter"> <evaluator> <expression>message.contains("str")</expression> </evaluator> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>D:/logs/contains.%d{yyyy-MM-dd}.log </FileNamePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder> <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern> </encoder> </appender> <!-- 数据库输出 --> <appender name="db" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> <url>jdbc:mysql://host_name:3306/datebase_name</url> <user>username</user> <password>password</password> </connectionSource> </appender> <logger name="java.sql.Connection"> <level value="DEBUG" /> </logger> <logger name="java.sql.Statement"> <level value="DEBUG" /> </logger> <logger name="com.ibatis"> <level value="DEBUG" /> </logger> <logger name="com.ibatis.common.jdbc.SimpleDataSource"> <level value="DEBUG" /> </logger> <logger name="com.ibatis.common.jdbc.ScriptRunner"> <level value="DEBUG" /> </logger> <logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate"> <level value="DEBUG" /> </logger> <logger name="com.danga.MemCached"> <level value="INFO" /> </logger> <logger name="org.springframework.test"> <level value="DEBUG" /> </logger> <logger name="org.apache.struts2"> <level value="DEBUG" /> </logger> <root level="DEBUG"> <appender-ref ref="stdout" /> <appender-ref ref="file—debug" /> <appender-ref ref="file—error" /> <appender-ref ref="file-str" /> <appender-ref ref="db" /> </root> </configuration>
备注:
作者:Shengming Zeng
博客:http://www.cnblogs.com/zengming/
本文是原创,欢迎大家转载;但转载时必须注明文章来源,且在文章开头明显处给明链接。
<欢迎有不同想法或见解的同学一起探讨,共同进步>