spring切面:注解:抛出异常增强

用注解定义增强
在项目中添加spring AOP相关的jar文件;
使用注解定义前置增强和后置增强实现日志功能;
编写spring配置文件,织入注解定义的增强。

1.aop/UserLogger注释增强类

package aop;

import java.util.Arrays;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.AfterReturning;


@Aspect
public class UserLogger {
	private static final Logger log = Logger.getLogger(UserLogger.class);
@Before("execution(* biz.impl.*.*(..))")
public void before(JoinPoint jp){
	System.out.println("注解前置增强");
	System.out.println("调用的方法:"+jp.getSignature()+",传递参数:"+Arrays.toString(jp.getArgs()));
}
@AfterReturning(pointcut="execution(* biz.impl.*.*(..))",returning="returnResult")
public void afterReturning(JoinPoint jp,Object returnResult){
	System.out.println("注解后置增强");
	System.out.println("调用的方法:"+jp.getSignature()+",传递参数:"+Arrays.toString(jp.getArgs())+",返回参数:"+returnResult);
}
@AfterThrowing(pointcut="execution(* biz.impl.*.*(..))",throwing="e")
public void afterThrowing(JoinPoint jp,RuntimeException e){

	log.error("调用的方法:"+jp.getSignature()+",传递参数:"+Arrays.toString(jp.getArgs())+",方法发生异常:"+e);
}
}

2.applicationContext.xml配置文件



 
	
	
	
	
    
      
    
   
   

3.dao.impl/UserDaoImpl类

package dao.impl;

import javax.management.RuntimeErrorException;

import dao.UserDao;
import entity.User;

public class UserDaoImpl implements UserDao {

	@Override
	public User findUser() {
		System.out.println("===========Dao层查询User 1==============");
		User u=new User("Tom",22);
		throw new RuntimeException("出现异常");
		//return u;
	}

}

4.Test方法

public static void main(String[] args) {
		
		//加载spring容器,解析配置文件
		ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
		 UserBiz userBiz=(UserBiz) ac.getBean("userBiz");
		 User u= userBiz.getUser(101);
		 System.out.println(u.getUname()+","+u.getAge());
	}

spring切面:注解:抛出异常增强_第1张图片

你可能感兴趣的:(Spring)