搜索
您的当前位置:首页正文

spring基于注解的Introduction

来源:二三娱乐

一、好言

一点一点疏远的原因,大概是 没有提前沟通 没有相互迁就 没有解释

二、

Spring中,Introduction的实现是通过将需要添加的新的行为逻辑,以新的接口定义增加到目标对象上。以@Aspect声明一个实列变量,它的类型对应的是新增加的接口类型,然后通过DeclareParents对其进行标注。通过@DeclareParents指定新接口定义的实现类以及将要加诸其上的目标对象。
IntroductionAspect .JAVA

@Component
@Aspect
public class IntroductionAspect {
    @DeclareParents(value = "org.mouse.spring.aspect.TaskImpl",defaultImpl = CounterImpl.class)
    public ICounter counter;
}
public interface ICounter {
    public String count();
}


@Service
public class CounterImpl implements ICounter {
    @Override
    public String  count() {
        System.out.println("--->=count()");
        return "hello world";
    }
}
public interface ITask {
    public void task();
}

@Service("task")
@Scope("prototype")
public class TaskImpl implements ITask {
    @Override
    public void task() {
        System.out.println("--->task()");
    }
}
public class IntroMain {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/aspect/aspect.xml");
        Object task = ctx.getBean("task");
        System.out.println(((ICounter)task).count());
    }
}
图片.png

Introduction 属于per-instance 类型的Advice,所以,还是不要忘记,目标对象的scope通常情况下应该设置prototype。

图片.png
Top