一个简单的AOP实例

x33g5p2x  于2021-11-13 转载在 其他  
字(2.8k)|赞(0)|评价(0)|浏览(564)
  1. 创建接口类:UserService.java
package com.liaoli.service;
public interface UserService {
	public void add();
	public void delete();
	public void update();
	public void select();
}
  1. 创建接口类的实现:UserServiceImpl.java
package com.liaoli.service;

public class UserServiceImpl implements UserService {
	public void add(){
		System.out.println("增加了一个用户");
	};
	public void delete(){
		System.out.println("删除了一个用户");
	};
	public void update(){
		System.out.println("修改了一个用户");
	};
	public void select(){
		System.out.println("查询了一个用户");
	};
}
  1. 对接口的每个方法,不改变代码的情况下,都增加一个日志功能:
    前置日志:Log.java
package com.liaoli.log;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class Log implements MethodBeforeAdvice {
	public void before(Method method, Object[] args, Object target) throws Throwable {
		System.out.println(target.getClass().getName()+"被执行了");
	}
}
后置日志:AfterLog.java
package com.liaoli.log;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;

public class AfterLog implements AfterReturningAdvice {
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		System.out.println("执行了:" + method.getName() + "返回结果为:" + returnValue);
	}
}
  1. 配置AOP的XML配置文件:applicationContext.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 https://www.springframework.org/schema/aop/spring-aop.xsd">
         
         
    <!-- 注册 bean-->
    <bean id="userService" class="com.liaoli.service.UserServiceImpl"/>
	<bean id="log" class="com.liaoli.log.Log"/>
	<bean id="afterLog" class="com.liaoli.log.AfterLog"/>
	
	<!-- 配置AOP 导入AOP的约束-->
	<aop:config>
	  <!--切入点:expression表达式 execution(要执行的位置) -->
	  <aop:pointcut id="pointcut" expression="execution(* com.liaoli.service.UserServiceImpl.*(..))"/>
	  <aop:advisor advice-ref="log" pointcut-ref="pointcut" />
	  <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut" />
	</aop:config>
</beans>
  1. 测试类
package com.liaoli.service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService userService = context.getBean("userService", UserService.class);
		userService.add();
	}
}
  1. 运行结果
    新增

删除

测试发现,接口的所有方法,都增加了日志功能。

相关文章