本文介绍介绍spring aop 的用法:注解和xml配置,最简洁的配置,最简单的介绍。
注解
使用注解去配置aop非常的简单,只需要在spring的xml配置文件里激活component-scan
功能指定需要扫描的包,将组件都初始化到spring的容器中。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/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:component-scan base-package="com.springinaction"/>
<!-- 激活自动代理功能 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
很简单,除了引入spring的一些命名空间外还有两行,一个是注册扫描功能并指定目标包、第二个是注册自动代理功能,这一点很重要,如果你不加入的话,spring就会抛出异常,我小白,没有能搞定其中的原理,在网上找了一个链接
动态代理
编写接口
这里声明一个接口Performance
,里面有perform()方法,如下
package com.springinaction.service;
public interface Performance {
public void perform();
}
编写Actor实现接口
这里需要加上conponent
的注解,是让spring初始化的时候被扫描到
package com.springinaction.service;
import org.springframework.stereotype.Component;
@Component
public class Actor implements Performance {
@Override
public void perform() {
System.out.println("表演中...");
}
}
编写一个切面
这个bean除了需要加上component
的注解外,还需要加上aspectj
的注解,让spring知道他不仅仅是一个组件,而且是一个切面。代码如下
package com.sp