package com.liaoli.service;
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
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("查询了一个用户");
};
}
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);
}
}
<?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>
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();
}
}
删除
测试发现,接口的所有方法,都增加了日志功能。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/vipshop_fin_dev/article/details/121294027
内容来源于网络,如有侵权,请联系作者删除!