`AOP`动态代理基于`xml`方式
AOP动态代理基于xml方式
步骤:
- 创建两个类,增强类和被增强类,创建方法
- 在Spring配置文件中创建两个类对象
- 在Spring配置文件中配置切入点
1.创建两个类,增强类和被增强类
被增强类:
public class Book { public void buy(){ System.out.println("book中方法。。。"); } }
增强类:
public class BookProxy { public void before(){ System.out.println("对Book中的buy方法进行增强。。。"); } }
2.在配置文件创建增强类和被增强类对象
<!--对增强类和被增强类进行配置--> <bean id="book" class="com.haikang.aopXml.Book"/> <bean id="bookProxy" class="com.haikang.aopXml.BookProxy"/>
3.在Spring配置文件中配置切入点和切面
<!--配置切入点和切面--> <aop:config> <!--切入点表示对Book类中的buy方法进行增强--> <aop:pointcut id="proxy" expression="execution(* com.haikang.aopXml.Book.buy(..))"/> <!--配置切面--> <aop:aspect ref="bookProxy"> <!-- 增强使用在具体的方法上,表示增强的方法是`BookProxy`中的`before`方法, pointcut-ref:表示是切面,与pointcut id="proxy",表示使用在Book类中的buy方法上 --> <aop:after method="before" pointcut-ref="proxy"/> </aop:aspect> </aop:config>
综合:
被增强类
public class Book { public void buy(){ System.out.println("book中方法。。。"); } }
增强类
public class BookProxy { public void before(){ System.out.println("对Book中的buy方法进行增强。。。"); } }
xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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="book" class="com.haikang.aopXml.Book"/> <bean id="bookProxy" class="com.haikang.aopXml.BookProxy"/> <!--配置切入点和切面--> <aop:config> <!--切入点表示对Book类中的buy方法进行增强--> <aop:pointcut id="proxy" expression="execution(* com.haikang.aopXml.Book.buy(..))"/> <!--配置切面--> <aop:aspect ref="bookProxy"> <!-- 增强使用在具体的方法上,表示增强的方法是`BookProxy`中的`before`方法, pointcut-ref:表示是切面,与pointcut id="proxy",表示使用在Book类中的buy方法上 --> <aop:after method="before" pointcut-ref="proxy"/> </aop:aspect> </aop:config> </beans>
test类
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("aspectsXml.xml"); Book book = context.getBean("book", Book.class); book.buy(); }
上一篇:
IDEA上Java项目控制台中文乱码