我正在使用SpringBoot开发Spring 4应用程序。
在com.test.tm包中, 应用程序类:
@SpringBootApplication @EnableJpaRepositories( repositoryFactoryBeanClass = GenericRepositoryFactoryBean.class ) @Import( { HikariDataSourceConfig.class } ) public class Application { public static void main( String[] args ) { SpringApplication.run(Application.class, args); } }
在com.test.tm.entities包中, 用户类别:
@Table( name = "test.user" ) @Entity public class User implements Serializable { @Id @GeneratedValue( strategy = GenerationType.AUTO ) private Integer id; private String message; .... }
在com.test.tm.user UserService.class中:
@Service @Transactional( rollbackFor = Exception.class ) public class UserService { @Autowired private GenericRepository<User, Serializable> gr; public User saveEntity( User usr ) { return gr.save(usr); } public String getUser() { //Get User logic } }
GenericRepository.java:
@NoRepositoryBean public interface GenericRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> { public List<T> findByNamedQuery( String name ); public List<T> findByNamedQueryAndParams( String name, Map<String, Object> params ); }
还有一种GenericRepositoryImpl.java实现上述方法的逻辑的地方。
GenericRepositoryImpl.java
在运行Application.java时,出现以下错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.test.utils.spring.repo.GenericRepository com.test.tm.user.UserService.gr; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type[com.test.utils.spring.repo.GenericRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.Dependency annotations: {@ org.springframework.beans.factory.annotation.Autowired(required = true) }
广告。1. userService如文档所示,Spring 使用默认名称创建bean 。
userService
广告。2.我不起诉,但是也许GenericRepositoryImpl不在 com.test.tm包裹内?如果是,则@ComponentScan使用正确的包声明指定其他注释,即。@ComponentScan("com.test.utils"),或者- 如果您使用的是Boot 1.3+-修改@SpringBootApplication(scanBasePackages={"com.test.utils","com.test.tm"})
GenericRepositoryImpl
com.test.tm
@ComponentScan
@ComponentScan("com.test.utils")
@SpringBootApplication(scanBasePackages={"com.test.utils","com.test.tm"})