- 命名空间的支持
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 注解
- 原代码
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");
}
}
No comments:
Post a Comment