首先,在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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- <bean id="bunShop" class="com.day10_24.dao.daoImpl.BunShopImpl"></bean>--> <!-- <bean id="shopService" class="com.day10_24.service.serviceImpl.BunShopServiceImpl">--> <!-- <property name="bunShop" ref="bunShop"></property>--> <!-- </bean>--> <!-- 开启基于注解的配置 --> <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy> <!-- 注解配置要扫描的包 --> <context:component-scan base-package="com.day10_24"></context:component-scan> </beans>
然后编写AOP切面类
package com.day10_24.AOPs; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class Aop { <!-- execution后面的为要增强的方法的路径以及参数的设定,可使用通配符 --> @Pointcut("execution(* com.day10_24.AOPs.IUserDaoImpl.sys())") public void testPoint(){ } @Before("testPoint()") public void testBefore() { System.out.println("testPoint() Before Success!"); } @After("testPoint()") public void testAfter() { System.out.println("testPoint() After Success!"); } }
接下来编写目标对象方法
package com.day10_24.AOPs; public interface IUserDao { public void sys(); }
package com.day10_24.AOPs; import org.springframework.stereotype.Component; @Component("iUserDaoImpl") public class IUserDaoImpl implements IUserDao { @Override public void sys() { System.out.println("hello World!"); } }
编写测试类
public class Test3 { public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext= new ClassPathXmlApplicationContext("applicationContext.xml"); IUserDao userDao=applicationContext.getBean("iUserDaoImpl", IUserDaoImpl.class); userDao.sys(); } }
打印结果: