首先搭建环境,
既然使用Annotation和AOP,第一步需要在.xml的配置文件中配置命名空间:我看了2.5的视频结合百度,配不好xml文件,最后发现官网上非常清楚,需要什么就在官网上看什么
<?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-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<strong> <context:annotation-config />
<context:component-scan base-package="com.bjsxt"/>
<aop:aspectj-autoproxy /> </strong>
</beans>
切面文件:这里要明白切面的一些标记及语法
@Aspect
@Component
public class LogInterceptor {
<strong>@Pointcut("execution(public * com.bjsxt.service..*.add(..))")</strong>
public void myMethod(){};
<strong>@Before("myMethod()")</strong>
public void before() {
System.out.println("method before");
}
<strong>@Around("myMethod()")</strong>
public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("method around start");
pjp.proceed();
System.out.println("method around end");
}
}
使用XML下的AOP
切面文件:将球面的注解去掉
@Aspect
@Component
public class LogInterceptor {
//@Pointcut("execution(public * com.bjsxt.service..*.add(..))")
public void myMethod(){};
//@Before("myMethod()")
public void before() {
System.out.println("method before");
}
//@Around("myMethod()")
public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("method around start");
pjp.proceed();
System.out.println("method around end");
}
}
.xml配置文件
<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/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.bjsxt"/>
<bean id="logInterceptor" class="com.bjsxt.aop.LogInterceptor"></bean>
<aop:config>
<aop:aspect id="logAspect" ref="logInterceptor">
<aop:before method="before" pointcut="execution(public * com.bjsxt.service..*.add(..))" />
</aop:aspect>
</aop:config>
</beans>
对于Annotation和xml配置的AOP来说,显然XML配置的AOP重要一些。对于别人项目中的类的注解不可见的情况下,只需要配置文件即可实现切面编程.