spring mvc aop配置事務的相關配置
阿新 • • 發佈:2019-02-11
一共四個配置檔案包括web.xml
spring-hibernate.xml
spring.xml<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/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:aop="http://www.springframework.org/schema/aop" xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd "> <!-- JNDI方式配置資料來源 --> <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> --> <!-- <bean id="sacheService" class="com.base.service.impl.ProductInfoServiceImpl"></bean> --> <!-- 配置資料來源 --> <bean id="dataSource" name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化連線大小 --> <property name="initialSize" value="0" /> <!-- 連線池最大使用連線數量 --> <property name="maxActive" value="20" /> <!-- 連線池最大空閒 --> <property name="maxIdle" value="20" /> <!-- 連線池最小空閒 --> <property name="minIdle" value="0" /> <!-- 獲取連線最大等待時間 --> <property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> --> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一個連線在池中最小生存的時間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 開啟removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分鐘 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 關閉abanded連線時輸出錯誤日誌 --> <property name="logAbandoned" value="true" /> <!-- 監控資料庫 --> <!-- <property name="filters" value="stat" /> --> <property name="filters" value="mergeStat" /> </bean> <!-- 配置hibernate session工廠 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">com.dialect.MysqlDialect</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> </props> </property> <!-- 自動掃描註解方式配置的hibernate類檔案 --> <property name="packagesToScan"> <list> <value>com.model</value> </list> </property> </bean> <!-- 配置事務管理器 --> <bean name="transactionManager" id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> <!-- 註解方式配置事物 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <context:annotation-config/> <!-- 攔截器方式配置事物 --> <!-- <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" rollback-for="java.lang.Exception"/> <tx:method name="save*" rollback-for="java.lang.Exception"/> <tx:method name="update*" rollback-for="java.lang.Exception"/> <tx:method name="modify*" rollback-for="java.lang.Exception"/> <tx:method name="edit*" rollback-for="java.lang.Exception"/> <tx:method name="delete*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="remove*" rollback-for="java.lang.Exception"/> <tx:method name="repair" rollback-for="java.lang.Exception"/> <tx:method name="deleteAndRepair" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="check*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="count*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> <tx:method name="get*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="find*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="load*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="search*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="datagrid*" propagation="SUPPORTS" rollback-for="java.lang.Exception"/> <tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> --> <bean id="aspectBean" class="com.aop.AopLog"></bean> <aop:config> <aop:aspect id="AopLog" ref="aspectBean"> <!--配置com.spring.service包下所有類或介面的所有方法--> <aop:pointcut id="businessService" expression="execution(* com.controller..*.*(..)) || execution(* com.base.service.impl.*.*(..))" /> <aop:before pointcut-ref="businessService" method="doBefore"/> <aop:after pointcut-ref="businessService" method="doAfter"/> <aop:around pointcut-ref="businessService" method="doAround"/> <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/> </aop:aspect> </aop:config> <!-- hiebernate中的hibernateTemplate模板方法 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <!-- 給HibernateTemplate類中注入 sessionFactory獲得例項 --> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 使用annotation 自動註冊bean,並檢查@Required,@Autowired的屬性已被注入 --> <!-- <context:component-scan base-package="com.base.dao,com.base.service,com.aop" /> --> </beans>
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <!-- 引入屬性檔案 --> <context:property-placeholder location="classpath:config.properties" /> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 自動掃描dao和service包(自動注入) --> <context:component-scan base-package="com.base.dao,com.base.service,com.aop" /> <!-- <bean class="zy.utils.DeleteTimer"></bean> --> </beans>
spring3mvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <context:annotation-config /> <context:component-scan base-package="com.controller"></context:component-scan> <!-- enable the configuration of transactional behavior based on annotations --> <!-- a PlatformTransactionManager is still required --> <!-- 設定multipartResolver才能完成檔案上傳 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="5000000000"></property> <property name="defaultEncoding" value="UTF-8" /> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" /> <bean id="aspectBean" class="com.aop.AopLog"></bean> <aop:aspectj-autoproxy proxy-target-class="true" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="com.jsonconvert.EageJacksonConverter" /> </list> </property> </bean> <!-- SpringMVC在超出上傳檔案限制時,會丟擲org.springframework.web.multipart.MaxUploadSizeExceededException --> <!-- 該異常是SpringMVC在檢查上傳的檔案資訊時丟擲來的,而且此時還沒有進入到Controller方法中 --> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- 遇到MaxUploadSizeExceededException異常時,自動跳轉到/WEB-INF/jsp/error_fileupload.jsp頁面 --> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">404</prop> </props> </property> </bean> <!-- <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/*admin*"/> <bean id="loginInterceptor" class="com.Sys.UserInterceptor"/> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/app/**"/> <bean id="appInterceptor" class="com.Sys.AppInterceptor"/> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/supapp/*"/> <bean id="supappInterceptor" class="com.Sys.SupAppInterceptor"/> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/forum*/**"/> <bean id="forumInterceptor" class="com.Sys.ForumInterceptor"/> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/b2c/**"/> <bean id="b2cInterceptor" class="com.Sys.B2CInterceptor"/> </mvc:interceptor> </mvc:interceptors> --> </beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>LANTIN</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
<span style="white-space:pre"> </span>classpath:spring/spring.xml,classpath:hibernate/spring-hibernate.xml
<span style="white-space:pre"> </span></param-value>
</context-param>
<servlet>
<servlet-name>spring3mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring3mvc</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/error.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error.html</location>
</error-page>
<error-page>
<error-code>401</error-code>
<location>/error.html</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/error.html</location>
</error-page>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- <listener>
<span style="white-space:pre"> </span> <listener-class>com.listener.SessionListener</listener-class>
<span style="white-space:pre"> </span></listener>
--> <filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name> flushMode </param-name>
<param-value>AUTO </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>login/login.html</welcome-file>
</welcome-file-list>
<session-config>
<span style="white-space:pre"> </span><session-timeout>0</session-timeout>
</session-config>
</web-app>
AopLog.java
package com.aop;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AopLog {
private static final Logger logger=Logger.getLogger(AopLog.class);
//@After("execution(* com.controller.*.*(..))")
public void doAfter(JoinPoint jp) {
// System.out.println("log Ending method: "
// + jp.getTarget().getClass().getName() + "."
// + jp.getSignature().getName());
logger.info("log Ending method: "
+ jp.getTarget().getClass().getName() + "."
+ jp.getSignature().getName());
/* LoggerUtil.info(jp.getClass(),jp.getTarget().getClass().getName() + "."
+ jp.getSignature().getName()+"[logo]:normal");*/
}
//@Around("execution(* com.controller.*.*(..))")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
long time = System.currentTimeMillis();
Object retVal = pjp.proceed();
time = System.currentTimeMillis() - time;
// System.out.println("process time: " + time + " ms");
logger.info("process time: " + time + " ms");
return retVal;
}
//@Before("execution(* com.controller.*.*(..))")
public void doBefore(JoinPoint jp) throws Exception {
logger.info("log Begining method: "
+ jp.getTarget().getClass().getName() + "."
+ jp.getSignature().getName());
// System.out.println("log Begining method: "
// + jp.getTarget().getClass().getName() + "."
// + jp.getSignature().getName());
}
//@AfterThrowing("execution(* com.controller.*.*(..))")
public void doThrowing(JoinPoint jp, Throwable ex) {
// System.out.println("method " + jp.getTarget().getClass().getName()
// + "." + jp.getSignature().getName() + " throw exception");
logger.info("method " + jp.getTarget().getClass().getName()
+ "." + jp.getSignature().getName() + " throw exception");
// System.out.println(ex.getMessage());
logger.info(ex.getMessage());
/*LoggerUtil.info(jp.getClass(),jp.getTarget().getClass().getName() + "."
+ jp.getSignature().getName()+"[logo]:exception"+ex.toString());*/
}
/* private void sendEx(JoinPoint jp,String ex) {
LoggerUtil.info(jp.getClass(),jp.getTarget().getClass().getName() + "."
+ jp.getSignature().getName()+"[logo]:exception"+ex);
} */
}
EageJacksonConverter.java
package com.jsonconvert;
import java.io.IOException;
import java.nio.charset.Charset;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.JavaType;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.Assert;
public class EageJacksonConverter extends AbstractHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private ObjectMapper objectMapper = new ObjectMapper();
private boolean prefixJson = false;
public EageJacksonConverter() {
super(new MediaType("application", "json", DEFAULT_CHARSET));
}
public void setObjectMapper(ObjectMapper objectMapper) {
Assert.notNull(objectMapper, "'objectMapper' must not be null");
this.objectMapper = objectMapper;
}
public void setPrefixJson(boolean prefixJson) {
this.prefixJson = prefixJson;
}
public boolean canRead(Class<?> clazz, MediaType mediaType) {
JavaType javaType = getJavaType(clazz);
return (this.objectMapper.canDeserialize(javaType))
&& (canRead(mediaType));
}
protected JavaType getJavaType(Class<?> clazz) {
return TypeFactory.type(clazz);
}
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return (this.objectMapper.canSerialize(clazz)) && (canWrite(mediaType));
}
protected boolean supports(Class<?> clazz) {
throw new UnsupportedOperationException();
}
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
JavaType javaType = getJavaType(clazz);
try {
return this.objectMapper
.readValue(inputMessage.getBody(), javaType);
} catch (JsonParseException ex) {
throw new HttpMessageNotReadableException("Could not read JSON: "
+ ex.getMessage(), ex);
}
}
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
JsonEncoding encoding = getEncoding(outputMessage.getHeaders()
.getContentType());
SerializerProvider serializerProvider = this.objectMapper
.getSerializerProvider();
serializerProvider.setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object arg0, JsonGenerator arg1,
SerializerProvider arg2) throws IOException,
JsonProcessingException {
arg1.writeObject("");
}
});
JsonGenerator jsonGenerator = this.objectMapper.getJsonFactory()
.createJsonGenerator(outputMessage.getBody(), encoding);
try {
if (this.prefixJson) {
jsonGenerator.writeRaw("{} && ");
}
this.objectMapper.writeValue(jsonGenerator, o);
} catch (JsonGenerationException ex) {
throw new HttpMessageNotWritableException("Could not write JSON: "
+ ex.getMessage(), ex);
}
}
private JsonEncoding getEncoding(MediaType contentType) {
if ((contentType != null) && (contentType.getCharSet() != null)) {
Charset charset = contentType.getCharSet();
for (JsonEncoding encoding : JsonEncoding.values()) {
if (charset.name().equals(encoding.getJavaName())) {
return encoding;
}
}
}
return JsonEncoding.UTF8;
}
}