Introduction是啥?在Spring中如果有一个已经存在的service,我们想对其进行增强,但是又不想改变其代码,这个时候就可以使用Introduction来处理。具体怎么实现,看下面的详细例子。
引入jar包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
<!--spring aop依赖AspectJ-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
</dependencies>
新建配置类
@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方法
工程结构