amework.stereotype.Component;
/**
* @author 李
* @version 1.0
*/
@Component
public class Camera implements UsbInterface {
@Override
public void work(String s) {
System.out.println("相机开始工作,参数是=" + s);
}
}
(4)配置容器文件:
<!--配置自动扫描的包-->
<context:component-scan base-package="com.li.aop.hw"/>
<!--开启基于注解的aop功能-->
<aop:aspectj-autoproxy/>
(5)MyAspect切面类:
package com.li.aop.hw;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* @author 李
* @version 1.0
* 切面类
*/
@Component
@Aspect
public class MyAspect {
//前置通知
@Before(value = "execution(public void com.li.aop.hw.*.work(String))")
public void beforeRunning(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("MyAspect前置通知-目标方法-" + methodName +
" 参数-" + Arrays.toString(joinPoint.getArgs()));
}
//其他通知逻辑相同,略
}
(6)测试类:
package com.li.aop.hw;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.annotations.Test;
/**
* @author 李
* @version 1.0
*/
public class UsbTest {
@Test
public void UsbAspectTest() {
ApplicationContext ioc = new ClassPathXmlApplicationContext("beans08.xml");
//获取的实际都是代理对象
UsbInterface phoneProxy = ioc.getBean("phone", UsbInterface.class);
UsbInterface cameraProxy = ioc.getBean("camera", UsbInterface.class);
phoneProxy.work("三星");
System.out.println("============");
cameraProxy.work("莱卡");
}
}
测试结果:
需要注意的是,如果测试类中使用接口类型获取bean,是因为当前ioc容器中只有一个代理对象。即只有一个类实现了SmartAnimal接口,因此这里只会有一个代理类。
如果有多个类实现接口,就不能使用接口类型获取bean。单例对象id默认分配的id是:id=类名(首字母小写)。或者通过自定义id来获取实现类的代理对象。