- 命名空間的支持
<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");
}
}