在Springmvc的工程中对DAO做切面来评估DAO的方法耗时时间

一、Spring的mvc配置以及使用
二、Spring的aop切面配置以及使用
三、Spring的aop切面在spring-mvc中失效的问题
四、通过aop切面来评估所有的dao在执行过程中的耗时

一、Spring的mvc配置以及使用
  a、在pom.xml中引入spring的jar包。
  b、在web.xml中配置,初始化dispatcherServlet,加载WebApplicationContext 容器。

<!-- 加载Springmvc得拦截器,初始化WebApplicationContext -->

<servlet>

<servlet-name>dispatcherServlet</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext-mvc.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>                <servlet-name>dispatcherServlet</servlet-name>                <url-pattern>*.action</url-pattern>        </servlet-mapping>
 c、在applicationContext-mvc.xml中配置视图解析器以及注解配置
        <!-- SpringMVC: 配置自动扫描的包 和 ViewResolver -->

<context:component-scan base-package="com.dhpei"></context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>

<property name="prefix" value="/WEB-INF/jsp/"/>

<property name="suffix" value=".jsp"/>

</bean> 
d、注解使用

@Controller

@RequestMapping("/user")

public class UserController  {

@Resource

private UserDao userDao;

@Resource

private SystemParamDao systemParamDao;

@RequestMapping("/userList")

public String userList(Model model,HttpServletRequest request,HttpServletResponse response){

Map<String,String> query=new HashMap<String,String>();

List<UserEntity> userList=userDao.findUserList(query);

List<SystemParamRowMapper> sexList=systemParamDao.getSystemParamByCategoryCode("sex");

model.addAttribute("sexList", sexList);

model.addAttribute("userList", userList);

return "user/userList";


}

访问:http://localhost:8080/knowledge/user/userList.action 得到访问页面。

二、Spring的aop切面配置以及使用

a、在pom.xml中引入spring的aop相关jar包以及aspectjrt和aspectjweaver对应version的jar包。

<!-- 加载Spring的容器,初始化ApplicationContext -->

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext.xml</param-value>

</context-param>

b、在web.xml中配置,加载ApplicationContext 容器。

<!-- 加载Spring的容器,初始化ApplicationContext -->

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext.xml</param-value>

</context-param>

c、在applicationContext.xml中配置aop切面

<!-- Spring: 配置自动扫描的包-->

<context:component-scan base-package="com.dhpei"/>

<!-- Spring的aop切面管理 -->

<bean id="logAspect" class="com.dhpei.utils.aop.LogAspect"/>

<aop:config>

<aop:aspect id="aspect" ref="logAspect">

<!--第一个*指任意返回值,第二个*指knowledge下面的任意包,第三个*指impl下面的任意的类,第四个*指任意方法-->

<aop:pointcut id="logpointcut" expression="execution(* com.dhpei.knowledge.*.dao.impl.*.*(..))"/>

<aop:around method="traceMethod"  pointcut-ref="logpointcut"/>

</aop:aspect>

</aop:config>

d、切面LogAspect

package com.dhpei.utils.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.ProceedingJoinPoint;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

public class LogAspect {

//切面方法

public Object traceMethod(final ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

Object returnVal = null;

final Logger log = getLog(proceedingJoinPoint);//获取当前执行的dao类的全称

final String methodName = proceedingJoinPoint.getSignature().getName();//获取当前dao类的执行方法
        long start=System.currentTimeMillis();

try {

if (log.isInfoEnabled()) {

final Object[] args = proceedingJoinPoint.getArgs();

final String arguments;

if (args == null || args.length == 0) {

arguments = "";

} else {

arguments = Arrays.deepToString(args);

}

log.info("进入方法 [" + methodName + "];参数 [" + arguments + "]");

}

returnVal = proceedingJoinPoint.proceed();

return returnVal;

} finally {

if (log.isInfoEnabled()) {

log.info("离开方法 [" + methodName + "] ;返回值 [" + (returnVal != null ? returnVal.toString() : "null") + "].");
                long end=System.currentTimeMillis();
                log.info("执行方法耗时:"+(end-start)+"毫秒。");

}

}

}

protected Logger getLog(final JoinPoint joinPoint) {

final Object target = joinPoint.getTarget();

if (target != null) {

return LoggerFactory.getLogger(target.getClass());

}

return LoggerFactory.getLogger(getClass());

}

}

三、Spring的aop切面在spring-mvc中失效的问题

将第一步和第二步的配置融合到一起使用,会发现aop切面执行不了。经过多方面调查原因,发现是由于Spring的mvc(WebApplicationContext 容器)在加载的过程中已经对dao对应的类做了扫描加载到容器中,当spring本身的(ApplicationContext 容器)再去扫描的时候发现已经加载到内存中,从而跳过了AOP的切面增强。

修改applicationContext-mvc.xml,添加excloud配置

<!-- SpringMVC: 配置自动扫描的包 和 ViewResolver -->

<context:component-scan base-package="com.dhpei">

<!-- 在Controller这一层加AOP增强 -->

<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>

</context:component-scan>

修改之后再启动工程,就可以正确的看到AOP的切面效果了。

四、通过aop切面来评估所有的dao在执行过程中的耗时

启动aop的切面之后,再次访问http://localhost:8080/knowledge/user/userList.action,可以看到debug日志如下:

2016.11.15 12:50:40 DEBUG CommonUtils - serviceUrl generated: http://localhost:8080/knowledge/user/userList.action

2016.11.15 12:50:40 DEBUG DispatcherServlet - DispatcherServlet with name ‘dispatcherServlet‘ processing GET request for [/knowledge/user/userList.action]

2016.11.15 12:50:40 DEBUG DefaultAnnotationHandlerMapping - Matching patterns for request [/user/userList.action] are [/user/userList.*]

2016.11.15 12:50:40 DEBUG DefaultAnnotationHandlerMapping - URI Template variables for request [/user/userList.action] are {}

2016.11.15 12:50:40 DEBUG DefaultAnnotationHandlerMapping - Mapping [/user/userList.action] to HandlerExecutionChain with handler [[email protected]] and 1 interceptor

2016.11.15 12:50:40 DEBUG DispatcherServlet - Last-Modified value for [/knowledge/user/userList.action] is: -1

2016.11.15 12:50:40 DEBUG HandlerMethodInvoker - Invoking request handler method: public java.lang.String com.dhpei.knowledge.user.controller.UserController.userList(org.springframework.ui.Model,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

2016.11.15 12:50:40 DEBUG AnnotationTransactionAttributeSource - Adding transactional method ‘UserDaoImpl.findUserList‘ with attribute: PROPAGATION_NOT_SUPPORTED,ISOLATION_DEFAULT,readOnly; ‘‘

2016.11.15 12:50:40 DEBUG DefaultListableBeanFactory - Returning cached instance of singleton bean ‘txManager‘

2016.11.15 12:50:40 DEBUG DefaultListableBeanFactory - Returning cached instance of singleton bean ‘logAspect‘

2016.11.15 12:50:40 INFO  UserDaoImpl - 进入方法 [findUserList];参数 [[{}]]

2016.11.15 12:50:40 DEBUG -UserDaoImpl- - execurte sql: select * from ts_user

2016.11.15 12:50:40 DEBUG JdbcTemplate - Executing SQL query [ select * from ts_user ]

2016.11.15 12:50:40 DEBUG DataSourceUtils - Fetching JDBC Connection from DataSource

2016.11.15 12:50:40 DEBUG DataSourceUtils - Registering transaction synchronization for JDBC Connection

2016.11.15 12:50:40 INFO  UserDaoImpl - 离开方法 [findUserList] ;返回值 [[UserEntity [id=1, userName=林肯, loginName=liken, password=670b14728ad9902aecba32e22fa4f6bd], UserEntity [id=2, userName=马克, loginName=make, password=32e22fa4f6bd670b14728ad9902aecba], UserEntity [id=3, userName=德克, loginName=deke, password=8ad9902aecba32e22670b1472fa4f6bd], UserEntity [id=4, userName=科林, loginName=kelin, password=70b14728ad9902aecba32e22fa4f6bd6]]].

2016.11.15 12:50:40 INFO  UserDaoImpl - 执行方法耗时:20毫秒。

2016.11.15 12:50:40 DEBUG DataSourceUtils - Returning JDBC Connection to DataSource

2016.11.15 12:50:40 DEBUG DefaultListableBeanFactory - Returning cached instance of singleton bean ‘logAspect‘

2016.11.15 12:50:40 INFO  SystemParamDaoImpl - 进入方法 [getSystemParamByCategoryCode];参数 [[sex]]

2016.11.15 12:50:40 DEBUG -SystemParamDaoImpl- - syp from db!

2016.11.15 12:50:40 DEBUG JdbcTemplate - Executing prepared SQL query

2016.11.15 12:50:40 DEBUG JdbcTemplate - Executing prepared SQL statement [ select type_code,type_name from ts_system_param where category_code=? ]

2016.11.15 12:50:40 DEBUG DataSourceUtils - Fetching JDBC Connection from DataSource

2016.11.15 12:50:40 DEBUG PreparedStatementPool - {conn-10001, pstmt-20001} enter cache

2016.11.15 12:50:40 DEBUG DataSourceUtils - Returning JDBC Connection to DataSource

2016.11.15 12:50:40 DEBUG -SystemParamDaoImpl- - category_code:scode;result:[SystemParamEntity [typeCode=0, typeName=男], SystemParamEntity [typeCode=1, typeName=女]]

2016.11.15 12:50:40 INFO  SystemParamDaoImpl - 离开方法 [getSystemParamByCategoryCode] ;返回值 [[SystemParamEntity [typeCode=0, typeName=男], SystemParamEntity [typeCode=1, typeName=女]]].

2016.11.15 12:50:40 INFO  SystemParamDaoImpl - 执行方法耗时:20毫秒。

2016.11.15 12:50:40 DEBUG Segment - put added 0 on heap

2016.11.15 12:50:40 DEBUG DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name ‘user/userList‘

2016.11.15 12:50:40 DEBUG DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name ‘user/userList‘; URL [/WEB-INF/jsp/user/userList.jsp]] in DispatcherServlet with name ‘dispatcherServlet‘

2016.11.15 12:50:40 DEBUG JstlView - Added model object ‘sexList‘ of type [java.util.ArrayList] to request in view with name ‘user/userList‘

2016.11.15 12:50:40 DEBUG JstlView - Added model object ‘userList‘ of type [java.util.ArrayList] to request in view with name ‘user/userList‘

2016.11.15 12:50:40 DEBUG Segment - fault removed 0 from heap

2016.11.15 12:50:40 DEBUG Segment - fault added 0 on disk

2016.11.15 12:50:40 DEBUG JstlView - Forwarding to resource [/WEB-INF/jsp/user/userList.jsp] in InternalResourceView ‘user/userList‘

2016.11.15 12:50:41 DEBUG DispatcherServlet - Successfully completed request

时间: 2024-08-02 20:01:06

在Springmvc的工程中对DAO做切面来评估DAO的方法耗时时间的相关文章

关于【cocos2dx-3.0beta-制作flappybird】教程在3.2工程中出现找不到CCMenuItem.h的解决方法

文章原文:http://blog.csdn.net/kantian_/article/details/36187141 作者升级源代码,可以在3.1平台下运行. 我的是vs2013+cocos2dx-3.2. 本来以为按照作者的方法新建工程后可以用,没想到总出现这个[无法打开包括文件: "CCMenuItem.h": No such file or directory]. 问题其实简单,就是找不到,这个找不到其实是没有在工程中包含要引用的头文件的文件路径.一般此类问题都是这样. 在  

Maven工程中自动拷贝资源文件的 pom文件配置方法

在pom文件中加入如下配置 <plugin> <artifactId>maven-resources-plugin</artifactId> <executions> <execution> <id>copy-resources</id> <phase>compile</phase> <goals> <goal>copy-resources</goal> <

C++中try_catch_throw的做异常处理

C++中try_catch_throw的做异常处理 选择异常处理的编程方法的具体原因如下: 1. 把错误处理和真正的工作分开来: 2. 代码更易组织,更清晰,复杂的工作任务更容易实现: 3. 毫无疑问,更安全了,不至于由于一些小的疏忽而使程序意外崩溃了: 4. 由于C++中的try catch可以分层嵌套,所以它提供了一种方法使得程序的控制流可以安全的跳转到上层(或者上上层)的错误处理模块中去.(不同于return语句,异常处理的控制流是可以安全地跨越一个或多个函数 ). 5. 还有一个重要的原

在一个项目中同时使用Swift和Objective-C代码混合编程的方法

主要介绍了在一个项目中同时使用Swift和Objective-C代码的方法,在一个工程中同时使用Swift和Objective-C混合语言编程的方法. Swift 与 Objective-C 的兼容能力使你可以在同一个工程中同时使用两种语言.你可以用这种叫做 mix and match 的特性来开发基于混合语言的应用,可以用 Swfit 的最新特性实现应用的一部分功能,并无缝地并入已有的 Objective-C 的代码中. Mix and Match 概述 Objective-C 和 Swift

Maven快速创建SpringMVC web工程详解(2)

一.前言 在上一篇文章中,讲解了如何用maven创建web工程,并简单搭建基于Spring框架的MVC工程,但是配置较为简单,很多配置尚未涉及:本文对 Spring MVC工程的更多详细配置.使用,进行进一步的讲解,搭建一个完整.可用的Spring web工程框架. 二.配置文件目录放置修改 根据maven工程提倡的标准目录结构,我们将/WEB-INF/目录下的Spring配置文件移到 /src/main/resources/ 目录下:而因为Spring默认加载的配置文件目录为/WEB-INF/

【Spring】Spring在JavaWeb工程中整合log4j

在<[Spring]Spring3.0.5的下载.配置与Helloworld>(点击打开链接)一文各位已经可能看到了.如果Spring不整合log4j直接启动,则会出现如下关于Spring整合log4j的警告.这个挺烦人的,一方面自己提倡高内聚,低耦合,另一方面,自己没有整合log4j就提出警告.我们程序猿写出来的程序就叫做"耦合",它Spring就叫做"整合".好吧!你只能同时搞明白,log4j是个什么鬼东西,Spring怎么整合log4j,两个问题:

MyBatis中如何通过继承SqlSessionDaoSupport来编写DAO(二)

(本文示例工程源代码下载地址:http://down.51cto.com/data/1975295) 在上一篇博文的最后,介绍了使用@PostConstruct注解标注StudentDao的init方法,这样在Spring完成依赖注入后此方法即会被Spring调用,从而也就完成了studentMapper的初始化工作. 如果只有StudentDao一个DAO类,这样做当然没有问题.不过在实际应用中,必定存在多个DAO类.每个DAO类的初始化方法,除了传入的映射器接口类型(如StudentMapp

MyBatis中如何通过继承SqlSessionDaoSupport来编写DAO(一)

在MyBatis中,当我们编写好访问数据库的映射器接口后,MapperScannerConfigurer就能自动成批地帮助我们根据这些接口生成DAO对象(),然后我们再使用Spring把这些DAO对象注入到业务逻辑层的对象(Service类的对象).因此,在这种情况下的DAO层,我们几乎不用编写代码,而且也没有地方编写,因为只有接口.这固然方便,不过如果我们需要在DAO层写一些代码的话,这种方式就无能为力了.此时,MyBatis-Spring提供给我们的SqlSessionDaoSupport类

在Qt工程中加Boost

摘要: Boost是一个很强大的C++库,堪比STL,里面有很多非常优秀的类库.我不多介绍,详情见官网:http://www.boost.org/ 要在我们的Qt工程中把这个库加进去应该怎么做呢?我今晚试了一下. Boost是一个很强大的C++库,堪比STL,里面有很多非常优秀的类库.我不多介绍,详情见官网:http://www.boost.org/ 要在我们的Qt工程中把这个库加进去应该怎么做呢?我今晚试了一下. 我从网上下载了Boost压缩文件,下载地址:boost_1_52_0.tar.g