设为首页 加入收藏

TOP

day09-AOP-02(四)
2023-07-25 21:42:59 】 浏览:63
Tags:day09-AOP-02
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("莱卡");
    }
}

测试结果:

image-20230125210719575

需要注意的是,如果测试类中使用接口类型获取bean,是因为当前ioc容器中只有一个代理对象。即只有一个类实现了SmartAnimal接口,因此这里只会有一个代理类。

如果有多个类实现接口,就不能使用接口类型获取bean。单例对象id默认分配的id是:id=类名(首字母小写)。或者通过自定义id来获取实现类的代理对象。

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇读Java8函数式编程笔记01_Lambda.. 下一篇LeetCode-343. 整数拆分 - 题解分..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目