我在应用程序上使用 Spring Boot (1.3.3) 和基于注解的/JavaConfig 配置。 我有以下存储库界面:
@RepositoryRestResource(collectionResourceRel = "something", path = "something")
public interface SomethingRepository
extends CrudRepository<SomethingRepository, Long> {
}
我想做的是覆盖生成的存储库代理中某些方法的行为。我发现这样做的唯一方法是基于文档建议的添加新自定义方法的内容(请参阅:Adding custom behavior to single repositories),因此我定义了以下接口(interface):
public interface SomethingRepositoryCustom {
Something findOne(Long id);
}
...然后我添加相应的实现:
public SomethingRepositoryImpl extends SimpleJpaRepository<Something, Long>
implements SomethingRepositoryCustom {
public SomethingRepositoryImpl(<Something> domainClass, EntityManager em) {
super(domainClass, em);
this.entityManager = em;
}
@Override
public Something findOne(Long id) {
System.out.println("custom find one");
// do whatever I want and then fetch the object
return null;
}
}
现在,如果我启动应用程序,我会收到以下错误:
... org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.dummy.repositories.SomethingRepositoryImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.dummy.repositories.SomethingRepositoryImpl.() ...
问题: 我该如何解决 BeanInstantiationException?我假设我需要声明一个存储库工厂 bean,但我不确定如何覆盖 Spring Boot 配置。
最佳答案
事实上,您必须在您的 @EnableJpaRepositories
注释中声明一个新的 FactoryBean:
@Configuration
@EnableJpaRepositories(value = "your_package",
repositoryFactoryBeanClass = CustomFactoryBean.class)
public class ConfigurationClass{}
CustomFactoryBean.java:
public class CustomFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I>{
@Override
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new SimpleJpaExecutorFactory(entityManager);
}
/**
* Simple jpa executor factory
* @param <T>
* @param <I>
*/
private static class SimpleJpaExecutorFactory<T, I extends Serializable> extends JpaRepositoryFactory{
private EntityManager entityManager;
/**
* Simple jpa executor factory constructor
* @param entityManager entity manager
*/
public SimpleJpaExecutorFactory(EntityManager entityManager) {
super(entityManager);
this.entityManager = entityManager;
}
@Override
protected Object getTargetRepository(RepositoryMetadata metadata) {
JpaEntityInformation entityInformation =
getEntityInformation(metadata.getDomainType());
return new SomethingRepositoryImpl<T,I>(entityInformation, entityManager);
}
@Override
protected Class getRepositoryBaseClass(RepositoryMetadata metadata) {
return SomethingRepositoryImpl.class;
}
}
}
然后它将是您的 SimpleJpaRepository
实例:SimpleJpaRepositoryImpl
将被使用
关于java - Spring 启动 : How to declare a custom repository factory bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36721601/