Spring总结 4.AOP之为对象添加新功能

时间:2023-12-22 09:53:50

  Spring除了提供增强原有功能的方法外,还提供了为一个对象引入新功能的方法。如下:

package cn.powerfully.service;

public interface IService {
public void doSomething(int num);
}
package cn.powerfully.service;

public class ServiceImpl implements IService {

    @Override
public void doSomething(int num) {
System.out.println("doSomething --" + num);
} }

  现在为该类的实例化对象引入新方法f()。首先先定义一个接口表示要引入该接口的方法:

package cn.powerfully.service;

public interface IExtraService {
public void f();
}

  既然要有引入新功能,除了接口那肯定还要实现类:

package cn.powerfully.service;

public class ExtraServiceImpl implements IExtraService {

    @Override
public void f() {
System.out.println("add");
} }

  接着使用<aop:declare-parents>标签进行配置:

<?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
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
"> <bean id="aspect" class="cn.powerfully.aspect.Aspect" /> <bean id="userService" class="cn.powerfully.service.ServiceImpl" /> <aop:config>
<aop:aspect ref="aspect">
<aop:declare-parents types-matching="cn.powerfully.service.IService+"
implement-interface="cn.powerfully.service.IExtraService"
default-impl="cn.powerfully.service.ExtraServiceImpl" />
</aop:aspect>
</aop:config> </beans>

  其中,types-matching表示需要引入新功能的目标类,IService+表示了实现了IService接口的类。implement-interface表示新增的接口,default-impl表示其接口默认实现类。

  这样,就完成所有配置。对它进行测试:

package cn.powerfully.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.powerfully.service.IExtraService;
import cn.powerfully.service.IService; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:beans.xml")
public class Demo { @Resource
private IService service; @Test
public void test1() throws Exception {
service.doSomething(1);
IExtraService s = (IExtraService)service;
s.f();
} }