DeclareParents可以用来给被代理对象添加一些方法,虽然不常用,但是在分析SpringAop源码的时候,对这里一头雾水,所以使用该文章记录下。目前SpringAop也给我们提供了两种实现方式。
定义NoMethodAspectBean
/**
* @author 周宁
* @Date 2019-07-23 16:43
*/
public class NoMethodAspectBean {
}
定义被代理类需要新增方法
/**
* @author 周宁
* @Date 2019-07-23 16:33
*/
public interface IDeclareParent {
void isANewMethod();
}
/**
* @author 周宁
* @Date 2019-07-23 16:34
*/
public class IDeclareParentImpl implements IDeclareParent{
@Override
public void isANewMethod() {
System.out.println("恭喜你喜提新方法一枚");
}
}
1.使用@Aspect实现DeclareParents
定义AspectDeclareParent.java
/**
* @author 周宁
* @Date 2019-07-23 16:34
*/
@Aspect
public class AspectDeclareParent {
@DeclareParents(value = "org.springframework.study.day13.NoMethodAspectBean", defaultImpl = IDeclareParentImpl.class)
private IDeclareParent iDeclareParent;
}
配置aspectDeclareTest.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" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy/>
<bean id="noMethodAspectBean" class="org.springframework.study.day13.NoMethodAspectBean"/>
<bean id="aspectDeclareParent" class="org.springframework.study.day13.AspectDeclareParent"/>
</beans>
测试
@Test
public void testAspectDeclare(){
ApplicationContext ac = new ClassPathXmlApplicationContext("aspectDeclareTest.xml");
NoMethodAspectBean aspectBean = ac.getBean(NoMethodAspectBean.class);
IDeclareParent iDeclareParent = (IDeclareParent) aspectBean;
iDeclareParent.isANewMethod();
}
2.使用aspect:declare-parents实现
添加aspectDeclareXmlTest.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" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="noMethodAspectBean" class="org.springframework.study.day13.NoMethodAspectBean"/>
<aop:config>
<aop:aspect>
<aop:declare-parents implement-interface="org.springframework.study.day13.IDeclareParent"
types-matching="org.springframework.study.day13.NoMethodAspectBean"
default-impl="org.springframework.study.day13.IDeclareParentImpl"/>
</aop:aspect>
</aop:config>
</beans>
编写测试类
@Test
public void testAspectDeclareXml(){
ApplicationContext ac = new ClassPathXmlApplicationContext("aspectDeclareXmlTest.xml");
NoMethodAspectBean aspectBean = ac.getBean(NoMethodAspectBean.class);
IDeclareParent iDeclareParent = (IDeclareParent) aspectBean;
iDeclareParent.isANewMethod();
}