您的位置:首页 > 编程语言 > Java开发

我的Spring之旅——(二)Spring AOP实现的两种方式

2017-04-13 19:52 369 查看
我在《我的Spring之旅--aop构建项目》中说了,最近在学习aop怎么用,到现在大概体会到了aop的好处,也使用了不同的方式实现了aop,所以趁着休息时间写一下这两天的学习过程、过程中遇见的问题和对应的解决方案。与君共勉!

一、需求:

1.搭建Spring+Maven项目(在《我的Spring之旅--aop构建项目》中已经实现)

2.编写UserService类,类中包括saveUser(String name,int age)和deleteUser(String name)方法

3.编写StudentService类,类中包括saveStudent(String name,int age)和deleteStudent(String name)方法

4.所有方法执行后都要打印日志,输出内容为“XXX方法已执行,参数为param1,param2...”

5.saveUser()和saveSttudent()的参数age,如果传入的值小于0,则不再执行方法,并且打印日志“XXX方法执行失败,age:{$age}”

注:{$age}中输出传入的参数的值

二、实现

1.项目构建

构建后的目录:



2.编写两个类

package lm.practice.services;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* Created by Administrator on 2017/4/11.
*/
public class StudentService {
Log log=LogFactory.getLog(this.getClass());
public void saveStudent(String name,int age){
System.out.println("保存了一个学生的信息");
}
public void deteleStudent(String name){
System.out.println("删除了一个学生的信息");
}
}


package lm.practice.services;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* Created by Administrator on 2017/4/11.
*/
public  class UserService {
Log log=LogFactory.getLog(this.getClass());
public  void saveUser(String name,int age){
System.out.println("保存了一个用户的信息");
}
public void deleteUser(String name)
{
System.out.println("删除了一个用户的信息");
}
}


3.实现切面

方法一:配置文件法

(1)在aop包中编写LogInterceptor类作为切面类

package lm.practice.aop;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;

/**
* Created by Administrato
4000
r on 2017/4/12.
*/

public class LogInterceptor {
private Log log= LogFactory.getLog(this.getClass());

/**
* 后置通知
* @param joinPoint  连接点
*/
public void after(JoinPoint joinPoint){
//获取执行的方法名
String methodName=joinPoint.getSignature().getName();
//获取方法的参数
Object[] objects=joinPoint.getArgs();

//在日志中输出
log.info(methodName+"方法执行了,参数为:");
for (Object object:objects){
log.info(object+" ");
}
}
}


(2)配置文件spring-aop.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> 
<!--将类注入到bean中-->
<!--切面-->
<bean id="logInterceptor" class="lm.practice.aop.LogInterceptor"></bean>

<bean id="studentService" class="lm.practice.services.StudentService"></bean>
<bean id="userService" class="lm.practice.services.UserService"></bean>

<aop:config>

<!--调用日志类-->
<!--配置在services包下的所有类都会被拦截-->
<aop:pointcut id="logService" expression="execution(* lm.practice.services.*.*(..))"/>
<!--expresstion中参数的含义:
lm.practice.services:包名
.*.*(..)表示该包下的所有类的所有方法,括号中的两个点表示参数没有限制
-->
<aop:aspect id="b" ref="logInterceptor">
<!--后置通知-->
<aop:after  method="after" pointcut-ref="logService"/>
</aop:aspect>
</aop:config>
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>


方法二:注解法

(1)切面类的写法

package lm.practice.aop;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
* Created by Administrator on 2017/4/12.
*/

/**
* 日志切面类
*/
@Aspect
public class LogInterceptor {
private Log log= LogFactory.getLog(this.getClass());

//定义切入点
@Pointcut("execution(* lm.practice.services.*.*(..))")
private void allMethod(){

}
/**
* 后置通知
* @param joinPoint  连接点
*/
@After("allMethod()")
public void after(JoinPoint joinPoint){
//获取执行的方法名
String methodName=joinPoint.getSignature().getName();
//获取方法的参数
Object[] objects=joinPoint.getArgs();

//在日志中输出
log.info(methodName+"方法执行了,参数为:");
for (Object object:objects){
log.info(object+" ");
}
}}


(2)配置文件的写法

<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> 
<!--将类注入到spring容器-->
<bean id="userService" class="lm.practice.services.UserService"></bean>
<bean id="studentService" class="lm.practice.services.StudentService"></bean>

<!--把切面类交由spring容器来管理-->
<bean id="logInterceptor" class="lm.practice.aop.LogInterceptor"></bean>

<!--启动spring对AspectJ注解的支持-->
<aop:aspectj-autoproxy/>
</beans>


4.测试类

package test;

import lm.practice.services.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
* Created by Administrator on 2017/4/12.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-aop.xml")
public class LonInterceptorTest {

@Autowired
private UserService userService;

@Test
public void test(){
userService.saveUser("dd",12);
}
/**
* -------------我是分界线,我上面的叫做注解测试方法,我下面的是传统的代码,都可以实现-----------------
*/
//    public static void main(String[] args){
//        ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-aop.xml");
//        UserService userService=ctx.getBean("userService",UserService.class);
//        userService.saveUser("小小",25);
//    }
}


5.运行结果:

(1)控制台输出



(2)日志文件

a.注解方式



b.main方法的方式



在实现这些功能的时候,中间为了搞清楚AOP通知的几种类型,以及类型的区别,犯了一些错误,我会在下一篇文章中做总结和说明,希望本篇博客达到了共勉的效果,也希望我们不断成长!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息