您的位置:首页 > 编程语言 > Java开发

使用Spring(11)使用Spring进行面向切面编程(AOP)Schema-based AOP support

2016-10-21 12:56 417 查看
使用XML格式

官方说明:

在Spring的配置文件中,所有的切面和通知器都必须定义在
<aop:config>
元素内部。 一个application context可以包含多个
<aop:config>
。 一个
<aop:config>
可以包含pointcut,advisor和aspect元素(注意它们必须按照这样的顺序进行声明)。

<aop:config>
风格的配置使得对Spring
auto-proxying 机制的使用变得很笨重。如果你已经通过
BeanNameAutoProxyCreator
或类似的东西使用显式的auto-proxying将会引发问题 (例如通知没有被织入)。推荐的使用模式是只使用
<aop:config>
风格或只使用
AutoProxyCreator
风格

1.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

<!-- 在Spring的配置文件中,所有的切面和通知器都必须定义在 <aop:config> 元素内部。 -->
<!-- 一个application context可以包含多个 <aop:config>。 -->
<!-- 一个 <aop:config> 可以包含pointcut,advisor和aspect元素(注意它们必须按照这样的顺序进行声明)。 -->

<!-- 声明一个切面 -->
<aop:config>
<aop:aspect id="myAspect" ref="aBean">

<!-- 声明一个切入点 -->

<aop:pointcut id="businessService" expression="execution(* test01(..))" />
<aop:before pointcut-ref="businessService" method="before" />

</aop:aspect>
</aop:config>

<bean id="aBean" class="com.yw.test09.AspectClass">

</bean>
<bean id="myclass" class="com.yw.test09.MyClass"></bean>

</beans>


2.

package com.yw.test09;

public class AspectClass
{
public void before()
{
System.out.println("==AOP==before===");
}
}

package com.yw.test09;

public class MyClass
{
public void transfer()
{
System.out.println("transfer==");
}

public void test01()
{
System.out.println("test01====");
}
}

package com.yw.test09;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test
{
public static void main(String[] args)
{
ApplicationContext app = new ClassPathXmlApplicationContext("classpath:com/yw/test09/applicationContext.xml");

// Schema-based AOP support
MyClass o = (MyClass) app.getBean("myclass");
o.transfer();
o.test01();
}
}


3.运行如图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: