我们大家都知道,mybatis的mapper接口,我们并没有手动编写实现代码,但仍然能在程序中注入到Spring容器并使用。这里面就用到了动态代理的原理。
下面,我也编写一个接口,代码未给出实现,通过动态代理进行接口的默认实现,通过FactoryBean方式注入到容器中(当然,我们也可以通过在一个用@Configuration声明的配置类中,通过@Bean注解,手动编写该实例的生成过程)。下面是代码实例。
代码结构如下图所示:
一、首先创建一个maven工程,引入相关依赖,这里我直接用的Springboot,编写一个TestService接口
package com.company.service;
import java.util.List;
public interface TestService {
List<String> getList(String code, String name);
}
二、创建一个ServiceInvocationHandler类,并实现invocationHandler接口。注意:这个类的invoke方法,我们可以在这个方法里面获取到接口被调用时的方法、参数以及方法的返回值等,并编写自定义方法实现的业务逻辑等。
package com.company.handler;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;
public class ServiceInvocationHandler implements InvocationHandler {
private Class<?> interfaceType;
public ServiceInvocationHandler(Class<?> intefaceType) {
this.interfaceType = interfaceType;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
System.out.println("if调用前");
return method.invoke(this,args);
}
System.out.println("调用前,参数:{}" + args);
Object result = Arrays.asList(args);
System.out.println("调用后,结果:{}" + result);
return result;
}
}
三、创建一个ServiceProxyFactory,并实现FactoryBean接口。该Bean有点特殊,它默认返回的是getObjectType()类型的一个实例。
package com.company.handler;
import com.company.service.TestService;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
@Component
public class ServiceProxyFactory implements FactoryBean<TestService>{
@Override
public TestService getObject() throws Exception {
Class<?> interfaceType = TestService.class;
InvocationHandler handler = new ServiceInvocationHandler(interfaceType);
return (TestService) Proxy.newProxyInstance(interfaceType.getClassLoader(),
new Class[] {interfaceType},handler);
}
@Override
public Class<?> getObjectType() {
return TestService.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
四、之后我们便可以,将testService注入到控制器中使用了
package com.company.controller;
import com.alibaba.fastjson.JSON;
import com.company.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/test")
public String getHello() {
List<String> reuslt = testService.getList("code123","name456");
return JSON.toJSONString(reuslt);
}
}
五、测试,并打断点,发现成功注入