Spring AOP 切面
注解的方式定义切面
定义一个切面
通过@Aspect注解定义一个切面
@Aspect
public class AspectsTest {
//里面包含切点和通知
}
@Aspect注解
@Retention(RetentionPolicy.RUNTIME)
//只能使用来类上
@Target({ElementType.TYPE})
public @interface Aspect {
String value() default "";
}
XML的方式定义切面
定义一个切面
创建一个切面的pojo
public class AspectsTest {
//实现了切面的功能
}
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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- 将切面pojo注入spring容器中 -->
<bean id="aspectstest" class="com.test.springdome01.AspectsTest"></bean>
<aop:config>
<!-- 定义aspectstest bean为一个切面 -->
<aop:aspect ref="aspectstest"></aop:aspect>
</aop:config>
</beans>
Spring如何发现这个切面
通过JavaConfig配置方式
@Configuration
//启用AspectJ自动代理
@EnableAspectJAutoProxy(proxyTargetClass=true)
@ComponentScan
public class SpringConfig {
}
通过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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--
注意上方:引入Spring-aop的约束
-->
<!-- 启用AspectJ自动代理 -->
<aop:aspectj-autoproxy />
</beans>