小编典典

BeancreationException + NosuchBeandefinition异常

spring-boot

我正在使用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实现上述方法的逻辑的地方。

在运行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的变量,但是仍然显示错误。
  2. 我可以通过任何方式解决上述问题。

阅读 363

收藏
2020-05-30

共1个答案

小编典典

广告。1. userService文档所示,Spring 使用默认名称创建bean 。

广告。2.我不起诉,但是也许GenericRepositoryImpl不在
com.test.tm包裹内?如果是,则@ComponentScan使用正确的包声明指定其他注释,即。@ComponentScan("com.test.utils"),或者-
如果您使用的是Boot
1.3+-修改@SpringBootApplication(scanBasePackages={"com.test.utils","com.test.tm"})

2020-05-30