Spring Aop的应用

大家好,这次我来讲一讲Spring Aop的几个常见应用。

     首先,我们共同来理解一下Spring Aop,为什么要有它呢,它可以替代OOP吗,它在开发中能给我们带来什么呢,它又有哪些应用呢,我们带着这些疑问一起探讨Spring Aop的知识。

    第一,在使用前需要加入相应的Spring包以及Spring依赖包: 
     主包:org.springframework.aop-3.0.5.RELEASE.jar与org.springframework.aspects-3.0.5.RELEASE.jar 
     依赖包:com.springsource.org.aopalliance-1.0.0.jar与com.springsource.net.sf.cglib-2.2.0.jar
    这里需要说一下 com.springsource.net.sf.cglib-2.2.0.jar,使用cglib中的类库可以实现 拦截具体的类,不光是接口例如,可以是Controller类,大家都知道jdk 的反射机制把,cglib的功能与它类似,比它更强大。

    第二,异常处理实现: 

 

Java代码
  1. public class MyException1 implements<SPAN style="COLOR: #ff6600"> HandlerExceptionResolver</SPAN>   
  2.  {   
  3. @Override  
  4. public ModelAndView resolveException(HttpServletRequest request,   
  5. HttpServletResponse response, Object arg2, Exception ex) {   
  6.     System.out.println("进入异常处理......");   
  7.           if (ex instanceof ArrayIndexOutOfBoundsException) {   
  8.           System.out.println(ex);   
  9.           request.setAttribute("error""发生了数组越界异常....");   
  10.           return new ModelAndView("/SpringAop/exception/error.jsp");   
  11.           } else if (ex instanceof RuntimeException) {   
  12.                          System.out.println(ex);   
  13.                request.setAttribute("error""发生了运行时异常....");   
  14.      return new ModelAndView("/SpringAop/exception/error.jsp");   
  15.             }   
  16.     return null;   
  17. }   
  18.   
  19. }  
public class MyException1 implements HandlerExceptionResolver
 {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object arg2, Exception ex) {
	System.out.println("进入异常处理......");
          if (ex instanceof ArrayIndexOutOfBoundsException) {
          System.out.println(ex);
          request.setAttribute("error", "发生了数组越界异常....");
          return new ModelAndView("/SpringAop/exception/error.jsp");
          } else if (ex instanceof RuntimeException) {
                         System.out.println(ex);
	           request.setAttribute("error", "发生了运行时异常....");
     return new ModelAndView("/SpringAop/exception/error.jsp");
            }
	return null;
}

}

    第三,基本拦截器实现:

 

Java代码
  1.   public class MyInterceptor implements HandlerInterceptor {
  2. public void afterCompletion(HttpServletRequest arg0,   
  3.     HttpServletResponse arg1, Object arg2, Exception arg3)   
  4.             throws Exception {   
  5.         System.out.println("执行后....");   
  6.     }   
  7. public void postHandle(HttpServletRequest arg0,    
  8. HttpServletResponse arg1,Object arg2, ModelAndView arg3)    
  9.                                         throws Exception {   
  10.         System.out.println("执行了......");   
  11.     }   
  12.   
  13. public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,Object arg2) throws Exception {   
  14.         System.out.println("执行前....");   
  15.         return false;   
  16. }  
public class MyInterceptor implements HandlerInterceptor {

public void afterCompletion(HttpServletRequest arg0,
	HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		System.out.println("执行后....");
	}
public void postHandle(HttpServletRequest arg0, 
HttpServletResponse arg1,Object arg2, ModelAndView arg3) 
                                        throws Exception {
		System.out.println("执行了......");
	}

public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,Object arg2) throws Exception {
		System.out.println("执行前....");
		return false;
}

    第四:以日志为例,实现使用注释实现AOP

 

    第一步: 在Spring 配置文件中加入注释

 

Java代码
<aop:aspectj-autoproxy />  
<aop:aspectj-autoproxy />

    第二步: 写一个日志代理

 

Java代码
@Before("pointCut()")   
  1. public void before(JoinPoint jp) {   
  2. // 获取目标类名   
  3. String className = jp.getTarget().getClass().toString();   
  4. className = className.substring(className.indexOf("com"));   
  5. // 获取目标方法签名   
  6. String signature = jp.getSignature().toString();   
  7. // 获取方法名   
  8. String methodName = signature.substring(signature.lastIndexOf(".") + 1,signature.indexOf("("));   
  9. // 获取方法参数名称   
  10. Object[] args = jp.getArgs();   
  11. if (args != null) {   
  12.      for (int i = 0; i < args.length; i++) {   
  13.     System.out.println("args[" + i + "] =" + args[i]);   
  14.       }   
  15. }   
  16. System.out.println("获取目标类名" + className);   
  17. System.out.println("获取目标方法签名" + signature);   
  18. System.out.println("获取方法名称" + methodName);   
  19.   
  20. }  
@Before("pointCut()")
public void before(JoinPoint jp) {
// 获取目标类名
String className = jp.getTarget().getClass().toString();
className = className.substring(className.indexOf("com"));
// 获取目标方法签名
String signature = jp.getSignature().toString();
// 获取方法名
String methodName = signature.substring(signature.lastIndexOf(".") + 1,signature.indexOf("("));
// 获取方法参数名称
Object[] args = jp.getArgs();
if (args != null) {
     for (int i = 0; i < args.length; i++) {
	System.out.println("args[" + i + "] =" + args[i]);
      }
}
System.out.println("获取目标类名" + className);
System.out.println("获取目标方法签名" + signature);
System.out.println("获取方法名称" + methodName);

}

 

    第五,事务管理

    第一步:修改Spring配置文件,加入以下代码

 

Java代码
<bean id="transactionManager"  
  1.     class="org.springframework.orm.hibernate3.HibernateTransactionManager">   
  2.     <property name="sessionFactory">   
  3.     <ref bean="sessionFactory" />   
  4.      </property>   
  5. </bean>  
<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory">
    <ref bean="sessionFactory" />
     </property>
</bean>

    主要是与数据库sessionFactory关联

 

    第二步:加入自动事务处理注解

 

Java代码
<tx:annotation-driven transaction-manager="transactionManager" />  
<tx:annotation-driven transaction-manager="transactionManager" />

    下面就可以在Service层在需要进行Spring事务管理的类或方法上加入@Transaction注解,这样再进行数据库处理时,就会自动与数据库保持一致。

 

    ok,今天就写这些,另外,Spring Aop是还有好多应用,希望大家共同进步,有好的用法,共同进步。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值