使用注解的方式进行代理
步骤1:在com.hello.dao包下新建一个CarDao接口以及他的实现类CarDaoImpl,具体代码如下:
CarDao接口:
package com.hello.dao;
public interface CarDao {
public void play();
}
CarDaoImpl实现类:
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
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">
步骤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;
//执行xml文件
@ContextConfiguration("classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class TestClass {
@Autowired
private CarDao cd;
@Test
public void test(){
cd.play();
}
}
执行applicationContext.xml之后就能通过注解的方式进行代理加强了