1.bean.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="org.sh.spring"></context:component-scan>
<aop:aspectj-autoproxy/>
</beans>
<aop:aspectj-autoproxy/>
aspectj 自动产生动态代理
要想自动织入 类必须有spring来管理
LogInterceptor.java
package org.sh.spring.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LogInterceptor {
@Before("execution(public void org.sh.spring.impl.IUserDAOImpl.save(org.sh.spring.model.User))")
public void before() {
System.out.println("method start...");
}
}
首先@Component 进行制动注入,然后@Aspect表明这是一个切面,
@Before("execution(public void org.sh.spring.impl.IUserDAOImpl.save(org.sh.spring.model.User))")
execution 表明执行,在执行参数中指定的方法之前必须先执行before方法,注意要将参数写清楚
测试程序
@Test
public void testSave() {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
UserServices ud = (UserServices)ctx.getBean("userservice");
User u = new User();
ud.save(u);
}
测试结果:
method start...
user saved