Spring xml方式的AOP
package com.aop;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
//切面类
public class LogInterceptor {
?
?? public void before() {
??? System.out.println("method start before");
?? }
?public void afterReturning() {
??System.out.println("method afterReturning");
?}
}
配置文件配置:
<?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: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-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 /><!-- 为spring加入标注支持 -->
??? <context:component-scan base-package="com" /><!-- 让spring在com.model包下自己去找bean -->
?? <bean id="logInterceptor" id="servicePointcut"/>
????? <aop:aspect id="logAspect" ref="logInterceptor">
????????? <aop:before method="before" pointcut-ref="servicePointcut" />
????? </aop:aspect>
????? -->
????? <!-- 写法二: -->
????? <aop:aspect id="logAspect" ref="logInterceptor">
????????? <aop:before method="before" pointcut="execution(public * com.service..*.*(..))" />
????? </aop:aspect>
?? </aop:config>
</beans>
?
测试类:
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.model.User;
import com.service.UserService;
public class TestSpringIoc {
?
?public static void main(String[] args) {
??ApplicationContext? context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
?? User user = new User();
????? user.setPassword("sss");
????? UserService service = (UserService)context.getBean("userService");
????? service.add(user);
?}
}
?
备注:Spring的Aop需要aspectjrt.jar,aspectjrtweaver.jar两个jar包!!