引入增强-Spring AOP给目标bean添加新方法、功能
引入增强:可以给已经存在的类增加方法、逻辑。 我们以一个简单的Person类,只能run,给他增加一个fly的方法。
- IPerson
public interface IPerson {
void run();
}
- Person
public class Person implements IPerson {
@Override
public void run() {
System.out.println("可以跑...");
}
}
以上是一个很简单的接口、实现类,拥有一个run方法。
我们还拥有一个定义了fly的接口:
- IFlying
public interface IFlying {
void fly();
}
现在我们的目标是不修改IPerson、Person来让Person拥有fly的功能。这里可以使用Spring AOP的动态引入增强通知实现。
继承DelegatingIntroductionInterceptor
让FlyImpl扩展DelegatingIntroductionInterceptor 来实现
- FlyImpl
public class FlyImpl extends DelegatingIntroductionInterceptor implements IFlying {
@Override
public void fly() {
System.out.println("我还会飞...");
}
}
配置代理
- application.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
">
<!--原始bean-->
<bean id="person" class="org.byron4j.demo.Person"/>
<!--引入增强,使得person拥有flyde方法-->
<bean id="fly" class="org.byron4j.demo.FlyImpl"/>
<!--配置ProxyFactoryBean-->
<bean id="proxyBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<!--引入的接口-->
<property name="interfaces" value="org.byron4j.demo.IFlying"/>
<!--包含增强逻辑的bean-->
<property name="interceptorNames" value="fly"/>
<!--目标增强bean-->
<property name="target" ref="person"/>
<property name="proxyTargetClass" value="true"/>
</bean>
</beans>
pom.xml
代码语言:javascript复制<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>compile</scope>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
测试
代码语言:javascript复制@Test
public void test(){
ApplicationContext applicationContext
= new ClassPathXmlApplicationContext("application.xml");
// 获得的是person
IPerson person = ((IPerson) applicationContext.getBean("proxyBean"));
IFlying flying = (IFlying) person;
flying.fly(); // 输出:我还会飞...
}