如何在 Spring 中自动连接接口或抽象类而无需实现



我需要在没有实现的情况下自动连接一个接口,有点像 @Repository标签功能。

@QueryRepository
public interface EddressBookDao {
@ReportQuery
public List<EddressBookDto> loadEddresses(@EqFilter("id") Long id);
}
@Autowired
private EddressBookDao eddressBookDao;
Result result = eddressBookDao.loadEddresses(1L);

我正在考虑在 ClassPathScan 期间以某种方式检测我的@QueryRepository注释eddressBookDao并在 Autowire 上注入EddressBookDao对象的代理。

现在,我使用以下方法以繁琐的方式实现此功能:

@Autowired
public ReportQueryInvocationHandler reportQuery;
private EddressBookDao eddressBookDao;
public EddressBookDao eddressBook(){
if (eddressBookDao == null) eddressBookDao = reportQuery.handle(EddressBookDao.class);
return eddressBookDao;
}

这是我创建代理的处理程序:

@Component
public class ReportQueryInvocationHandler implements InvocationHandler {
public <T> T handle(Class<T> clazz){
return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws NoSuchFieldException, IllegalAccessException {
Type returnType = method.getReturnType();
Annotation[][] annotations = method.getParameterAnnotations();
Report report = dao.createReport();
for (int i = 0; i < args.length; i++) {
Object argument = args[i];
Annotation[] annotationList = annotations[i];
if (annotationList.length == 0) continue;
for (Annotation annotation : annotationList) {
Class<? extends Annotation> annotationType = annotation.annotationType();
String path = null;
if (annotationType.equals(EqFilter.class)) {
path = ((EqFilter) annotation).value();
report.equalsFilter(path, argument);
break;
} 
}
} 
return report.list((Class<?>) returnType);
}

这是我如何称呼我的它:

List<EddressBookDto> addressed = dao.eddressBook().loadEddresses(8305L);

我想要的只是避免编写此代码

private EddressBookDao eddressBookDao;
public EddressBookDao eddressBook(){
if (eddressBookDao == null) eddressBookDao = reportQuery.handle(EddressBookDao.class);
return eddressBookDao;
}

并写这个:

@Autowired
private EddressBookDao eddressBookDao;

Spring Data不会自动连接接口,尽管它可能看起来像这样。它注册生产实现接口的代理的工厂。

要执行类似操作,您必须实现FactoryBean接口。 有关详细信息,请参阅 JavaDoc。还有可用的教程。

最新更新