我有一个接口
interface MyInterface {
@MyAnnotation
void myMethod();
}
这个接口没有实现,也不想一个个写实现。
实现想用spring下的技术动态生成。
然后有另一个类注入了这个接口
class Test {
@Autowired MyInterface proxy;
public void test() {
proxy.myMethod();
}
}
请问这样子应该如何实现和配置?
Spring Data JPA 就是这样实现的,但我没看懂源码,希望能提供简单的实现
我自己写了个实现在下面,但每个需要代理实现的接口都得手动写一个create bean方法。
有没有像Spring Data JPA那样直接扫描某个包和注解自动创建bean的办法?
@Autowired 不是动态实现
实现还是要你自己实现
用一个类继承接口,便于初始化,然后用aop技术,自动生成那个基本类的代理,这样既可以用xml配置,也可以用注解配置,符合你的要求吗?
我自己作了一个实现
@Configuration
public class MyInterfaceImplFactory {
@Bean
public MyInterface getMyInterface() {
return getProxy(MyInterface.class);
}
<T> T getProxy(Class<T> clazz) {
return (T) Proxy.newProxyInstance(ProxyImpl.class.getClassLoader(), new Class<?>[] {clazz}, new ProxyImpl());
}
class ProxyImpl implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MyAnnotation myAnnotation = methdo.getAnnotation(MyAnnotation.class);
// do something
return null;
}
}
}
但这样做必须每一个要代理实现的接口都得写一个create bean方法。
有没有像Spring Data JPA那样直接扫描某个包和注解自动创建bean的办法?