栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring AOP中Introduction的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring AOP中Introduction的使用

Introduction是啥?在Spring中如果有一个已经存在的service,我们想对其进行增强,但是又不想改变其代码,这个时候就可以使用Introduction来处理。具体怎么实现,看下面的详细例子。

引入jar包

 

        
            org.springframework
            spring-context
            5.1.4.RELEASE
        

        
        
            org.aspectj
            aspectjweaver
            1.9.2
        

    

新建配置类

@Configuration
@ComponentScan("com.xqc")
@EnableAspectJAutoProxy
public class IntroductionConfig {


}

新建接口OrderInterface并添加say方法

public interface OrderInterface {

    void say();
}

实现类

@Service
public class OrderInterfaceImpl implements OrderInterface{
    @Override
    public void say() {
        System.out.println("say...");
    }
}

新建OrderServiceImpl类,

@Service
public class OrderServiceImpl {

}

可以看出该类中没有任何方法,但是我们又想使用say方法。需要添加切面类,然后使用@DeclareParents注解

@Aspect
@Component
public class IntroductionAspect {

    @DeclareParents(value = "com.xqc.introduction.OrderServiceImpl",defaultImpl = OrderInterfaceImpl.class)
    private OrderInterface orderInterface;

}
value:写需要增强的类,支持表达式
defaultImpl:具体实现增强方法的的类

结果输出

public class TestIntroduction {
        public static void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(IntroductionConfig.class);
            OrderInterface orderInterface = (OrderInterface)context.getBean(OrderServiceImpl.class);
            System.out.println(orderInterface);
            orderInterface.say();

        }
}

 成功调用OrderInterfaceImpl的say方法


工程结构

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/490131.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号