第三种实现方法—通过注解来实现
beans.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 id="userService" class="cn.sxt.service.impl.UserServiceImpl"></bean>
<bean id="log" class="cn.sxt.log.Log"/>
<aop:aspectj-autoproxy/>
</beans>
log.java
package cn.sxt.log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class Log {
@Before("execution(* cn.sxt.service.impl.*.*(..))")
public void before() {
System.out.println("------方法执行前------");
}
@After("execution(* cn.sxt.service.impl.*.*(..))")
public void after() {
System.out.println("------方法执行后------");
}
@Around("execution(* cn.sxt.service.impl.*.*(..))")
public Object around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
System.out.println("签名:"+jp.getSignature());
//执行目标方法
Object result=jp.proceed();
System.out.println("环绕后");
return result;
}
}
Test.java
package cn.sxt.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.sxt.service.UserService;
public class Test {
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
UserService userService =(UserService)ac.getBean("userService");
userService.delete();
}
}
UserServiceImpl.java
package cn.sxt.service.impl;
import cn.sxt.service.UserService;
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("------添加用户数据------");
}
public int delete() {
System.out.println("------删除用户数据------");
return 1;
}
}