Log.java
package com.atstudy.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
/**
* 该AOP由于实现了接口,很大概率Spring使用JDK动态代理
*/
public class Log implements MethodBeforeAdvice
{
/**
*
* @param method 被调用方法的对象
* @param args 被调用方法的参数
* @param target 被调用方法的目标对象---实际对象
* @throws Throwable
*/
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("调用了"+target.getClass().getName()+"的"+method.getName()+"方法...");
}
}
spring.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="userDao" class="com.atstudy.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.atstudy.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="controller" class="com.atstudy.controller.UserController">
<property name="userService" ref="userService"></property>
</bean>
<!--上面是自动注入-->
<!--log负责通知的类代码-->
<bean id="log" class="com.atstudy.log.Log"></bean>
<!--配置AOP-->
<aop:config>
<!--
配置切入点
expression表示指定从当前工程的那个地方进行切入完成AOP
execution()配置切入点表达式
execution(* com.atstudy.controller.*.*(..))
第一个*星号表示所有的返回值类型
第二个*星号表示controller包中的所有的类
第三个*星号表示controller包中所有类的所有方法名
..两点表示所有方法中的所有的参数类型以及参数个数,注意只能是两点
-->
<aop:pointcut id="ponintcut" expression="execution(* com.atstudy.controller.*.*(..))"/>
<!--配置通知,advisor表示使用通知,advice-ref使用那个业务作为通知,pointcut-ref该通知的切入点-->
<aop:advisor advice-ref="log" pointcut-ref="ponintcut"></aop:advisor>
</aop:config>
</beans>
测试代码块
UserControllerTesting.java
package com.atstudy.test;
import com.atstudy.controller.UserController;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserControllerTesting
{
public static void main(String[] args) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring.xml");
UserController userController = (UserController) beanFactory.getBean("controller");
userController.query();
}
}