使用注解的方式進(jìn)行代理
步驟1:在com.hello.dao包下新建一個CarDao接口以及他的實(shí)現(xiàn)類CarDaoImpl圃庭,具體代碼如下:
CarDao接口:
package com.hello.dao;
public interface CarDao {
????public void play();
}
CarDaoImpl實(shí)現(xiàn)類:
package com.hello.dao;
@Component("CarDao")? ???//注解
public class CarDaoImpl implements CarDao {
????????@Override
????????public void play() {
????????????????System.out.print("我能跑120km/h");
????????}
}
步驟2:新建一個com.hello.plus包并在包下新建一個名為CarPlus的類
package com.hello.plus;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
@Aspect? ? //注解
public class CarPlus {
@After(value="execution(* *..*.*Impl.play(..))")????????//注解
public void carplus(){
System.out.println("我能飛上天");
}
}
這上面兩個地方使用了注解
步驟3:在src下新建一個xml文件applicationContext.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.xsd
? ? ? ? http://www.springframework.org/schema/context
? ? ? ? http://www.springframework.org/schema/context/spring-context.xsd
? ? ? ? http://www.springframework.org/schema/aop
? ? ? ? http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 加載自動代理 -->
<aop:aspectj-autoproxy/>
<!-- 注解掃描 -->
<context:component-scan base-package="com.hello"/>
<!-- 將 MyPlus 類交給 Spring 管理 -->
<bean id="CarPlus" class="com.hello.plus.CarPlus"></bean>
<!-- 切面 = 切入點(diǎn) + 通知
表達(dá)式優(yōu)化:
1)省略 public
2)返回值荷逞,不能省略,但可以使用 * 占位
3)如果中間的路徑太多的話餐蔬,則可以使用 *..*
4)如果有多個 類/方法 的 前/后綴 是相同的話,也可以使用 前/后綴 作為過濾條件
5)如果方法中有0 - 多個參數(shù)(不確定個數(shù)的參數(shù))灯帮,則可以直接使用兩個點(diǎn)表示
-->
<!-- <aop:config>
<aop:aspect ref="carPlus">
<aop:after method="carplus" pointcut="execution(* *..*.*Impl.play(..))"/>
</aop:aspect>
</aop:config> -->
</beans>
步驟4:接下來就是測試了爆土,新建一個測試類TestClass
package com.hello.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.hello.dao.CarDao;
//執(zhí)行xml文件
@ContextConfiguration("classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class TestClass {
@Autowired
private CarDao cd;
@Test
public void test(){
????cd.play();
}
}
執(zhí)行applicationContext.xml之后就能通過注解的方式進(jìn)行代理加強(qiáng)了