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

Spring v3.0.2 Learning Note 13 - AOP Example

2010-10-25 11:15 246 查看
命名空间的支持

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

<context:component-scan base-package="com.spring.test" />

<aop:aspectj-autoproxy />

// AOP中这2个Bean的定义不可少!不明为什么,我定义了类路径的自动扫描了

<bean id="personAopImpl" class="com.spring.test.aop.PersonAopImpl" />

<bean id="personAopProxy" class="com.spring.test.aop.PersonAopProxy" />

</beans>

Aspect 注解

<aop:aspectj-autoproxy />

原代码

接口:

package com.spring.test.aop;

public interface IPersonAop {

public void sayHello(String name);

}

实现类:

package com.spring.test.aop;

import org.springframework.stereotype.Service;

@Service

public class PersonAopImpl implements IPersonAop {

@Override

public void sayHello(String name) {

System.out.println("Hello," + name);

}

}

代理类:

package com.spring.test.aop;

import org.aspectj.lang.annotation.After;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Before;

@Aspect

public class PersonAopProxy {

@Before("execution (* com.spring.test.aop..*.*(..))")

public void before() {

System.out.println("before...");

}

@After("execution (* com.spring.test.aop..*.*(..))")

public void after() {

System.out.println("after...");

}

}

测试类:

package com.spring.test.junit;

import org.junit.AfterClass;

import org.junit.BeforeClass;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.test.aop.IPersonAop;

public class AopTest {

@BeforeClass

public static void setUpBeforeClass() throws Exception {

}

@AfterClass

public static void tearDownAfterClass() throws Exception {

}

@Test

public void test(){

ApplicationContext ctx = new ClassPathXmlApplicationContext(

"spring.xml");

IPersonAop aop = (IPersonAop)ctx.getBean("personAopImpl");

aop.sayHello("xxxxx");

}

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