我正在尝试在春季启动时为我的项目定义架构
我要做的是创建一个从JpaRepository扩展的通用存储库
public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
}
然后,每个EntityDao将从BaseRepository扩展
@Repository
public interface AuthorityDao extends BaseRepository<Authority, Long> {
Authority findById(Long idRole);
Authority findByRoleName(String findByRoleName);
}
这是我在存储库层上执行此操作的方式。在服务层,我创建了一个名为GenericService的类,该类实现了IGenericService,并将BaseRepository注入其中:
@Service
public class GenericService<T, D extends Serializable> implements IGenericService<T, D> {
@Autowired
@Qualifier("UserDao")
private BaseRepository<T, D> baseRepository;
// implemented method from IGenericService
}
每个服务将从GenericService扩展:
public class AuthorityService extends GenericService<Authority, Long> implements IAuthorityService {
@Autowired
GenericService<Authority, Long> genericService;
运行项目时,出现此错误:
申请无法开始
说明:
fr.java.service.impl.GenericService中的baseRepository字段需要一个类型为'fr.config.daogeneric.BaseRepository'的bean。
操作:
考虑在您的配置中定义类型为“ fr.config.daogeneric.BaseRepository”的bean。
我该如何解决这个问题?
更新:
@SpringBootApplication
@EntityScan("fr.java.entities")
@ComponentScan("fr.java")
@EnableJpaRepositories("fr.java")
@EnableScheduling
@EnableAsync
@PropertySource({ "classpath:mail.properties", "classpath:ldap.properties" })
@EnableCaching
@RefreshScope
public class MainApplication extends SpringBootServletInitializer {
private static final Logger log = LoggerFactory.getLogger(MainApplication.class);
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MainApplication.class);
}
public static void main(String[] args) {
log.debug("Starting {} application...", "Java-back-end-java");
SpringApplication.run(MainApplication.class, args);
}
}
答案 0 :(得分:0)
您遇到了这个问题,因为您将GenericService
创建为bean并尝试注入BaseRepository
,但是Spring无法做到这一点,因为尚不清楚参数BaseRepository
是由哪些类构成的
从我这边,我建议您下一步:首先,GenericService
不应该是豆子,他所有的孩子都应该是豆子,您应该避免在孩子中注入GenericService
类,他们已经扩展了它。您的GenericService
应该是抽象的,它可以有抽象方法getRepository
,该方法将在GenericService
内部使用,存储库的注入将在GenericService
子类中完成。
所以你应该有这样的东西:
public abstract class GenericService<T, D extends Serializable> implements IGenericService<T,D> {
abstract BaseRepository<T, D> getRepository();
}
@Service
public class AuthorityService extends GenericService<Authority, Long> implements IAuthorityService {
@Autowired
BaseRepository<Authority, Long> baseRepository;
public BaseRepository<Authority, Long> getRepository() {
retrurn baseRepository;
}
}