Java UnsatisfiedDependencyException:使用名称创建 bean 时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41511511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:27:16  来源:igfitidea点击:

UnsatisfiedDependencyException: Error creating bean with name

javaspringspring-mvc

提问by kopylov

For several days I'm trying to create Spring CRUD application. I'm confused. I can't solve this errors.

几天来,我一直在尝试创建 Spring CRUD 应用程序。我糊涂了。我无法解决这些错误。

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clientController': Unsatisfied dependency expressed through method 'setClientService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clientService': Unsatisfied dependency expressed through field 'clientRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.kopylov.repository.ClientRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“clientController”的 bean 时出错:通过方法“setClientService”参数 0 表示的不满意依赖;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为 'clientService' 的 bean 时出错:通过字段 'clientRepository' 表达的不满意依赖;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“com.kopylov.repository.ClientRepository”类型的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

and this

和这个

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'clientService': Unsatisfied dependency expressed through field 'clientRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.kopylov.repository.ClientRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“clientService”的bean时出错:通过字段“clientRepository”表达的不满意依赖;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“com.kopylov.repository.ClientRepository”类型的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

ClientController

客户端控制器

@Controller
public class ClientController {
private ClientService clientService;

@Autowired
@Qualifier("clientService")
public void setClientService(ClientService clientService){
    this.clientService=clientService;
}
@RequestMapping(value = "registration/add", method = RequestMethod.POST)
public String addUser(@ModelAttribute Client client){
    this.clientService.addClient(client);
return "home";
}
}

ClientServiceImpl

客户服务接口

@Service("clientService")
public class ClientServiceImpl implements ClientService{

private ClientRepository clientRepository;

@Autowired
@Qualifier("clientRepository")
public void setClientRepository(ClientRepository clientRepository){
    this.clientRepository=clientRepository;
}



@Transactional
public void addClient(Client client){
    clientRepository.saveAndFlush(client);
}
}

ClientRepository

客户端存储库

public interface ClientRepository extends JpaRepository<Client, Integer> {

}

I looked through a lot of similar questions, but no one answer to them can't help me.

我浏览了很多类似的问题,但没有人回答他们不能帮助我。

采纳答案by Alex Roig

The ClientRepository should be annotated with @Repositorytag. With your current configuration Spring will not scan the class and have knowledge about it. At the moment of booting and wiring will not find the ClientRepository class.

ClientRepository 应该用@Repository标签注释。使用您当前的配置,Spring 不会扫描类并了解它。在启动和接线的时候不会找到 ClientRepository 类。

EDITIf adding the @Repositorytag doesn't help, then I think that the problem might be now with the ClientServiceand ClientServiceImpl.

编辑如果添加@Repository标签没有帮助,那么我认为问题现在可能出在ClientServiceand 上ClientServiceImpl

Try to annotate the ClientService(interface) with @Service. As you should only have a single implementation for your service, you don't need to specify a name with the optional parameter @Service("clientService"). Spring will autogenerate it based on the interface' name.

尝试ClientService@Service. 由于您的服务应该只有一个实现,因此您无需使用可选参数 指定名称@Service("clientService")。Spring 将根据接口的名称自动生成它。

Also, as Bruno mentioned, the @Qualifieris not needed in the ClientControlleras you only have a single implementation for the service.

此外,正如布鲁诺所提到的,@Qualifier不需要 ,ClientController因为您只有一个服务实现。

ClientService.java

客户端服务.java

@Service
public interface ClientService {

    void addClient(Client client);
}

ClientServiceImpl.java(option 1)

ClientServiceImpl.java(选项 1)

@Service
public class ClientServiceImpl implements ClientService{

    private ClientRepository clientRepository;

    @Autowired
    public void setClientRepository(ClientRepository clientRepository){
        this.clientRepository=clientRepository;
    }

    @Transactional
    public void addClient(Client client){
        clientRepository.saveAndFlush(client);
    }
}

ClientServiceImpl.java(option 2/preferred)

ClientServiceImpl.java(选项 2/首选)

@Service
public class ClientServiceImpl implements ClientService{

    @Autowired
    private ClientRepository clientRepository;

    @Transactional
    public void addClient(Client client){
        clientRepository.saveAndFlush(client);
    }
}

ClientController.java

客户端控制器.java

@Controller
public class ClientController {
    private ClientService clientService;

    @Autowired
    //@Qualifier("clientService")
    public void setClientService(ClientService clientService){
        this.clientService=clientService;
    }

    @RequestMapping(value = "registration", method = RequestMethod.GET)
    public String reg(Model model){
        model.addAttribute("client", new Client());
        return "registration";
    }

    @RequestMapping(value = "registration/add", method = RequestMethod.POST)
    public String addUser(@ModelAttribute Client client){
        this.clientService.addClient(client);
    return "home";
    }
}

回答by Sergio

Add @Repository annotation to the Spring Data JPA repo

向 Spring Data JPA 存储库添加 @Repository 注解

回答by Dmitry Gorkovets

According to documentationyou should set XML configuration:

根据文档,您应该设置 XML 配置:

<jpa:repositories base-package="com.kopylov.repository" />

回答by Bruno Delor

Considering that your package scanning is correctly set either through XML configuration or annotation based configuration.

考虑到您的包扫描是通过 XML 配置或基于注释的配置正确设置的。

You will need a @Repositoryon your ClientRepositoryimplementation as well to allow Spring to use it in an @Autowired. Since it's not here we can only suppose that's what's missing.

您还需要@Repository在您的ClientRepository实现中使用a以允许 Spring 在@Autowired. 既然它不在这里,我们只能假设这就是缺少的东西。

As a side note, it would be cleaner to put your @Autowired/@Qualifierdirectly on your member if the setter method is only used for the @Autowired.

作为一个侧面说明,这将是更清洁把你的@Autowired/@Qualifier直接在您的部件上,如果setter方法仅用于@Autowired

@Autowired
@Qualifier("clientRepository")
private ClientRepository clientRepository;

Lastly, you don't need the @Qualifieris there is only one class implementing the bean definition so unless you have several implementation of ClientServiceand ClientRepositoryyou can remove the @Qualifier

最后,您不需要@Qualifier只有一个类实现 bean 定义,因此除非您有多个实现ClientService并且ClientRepository可以删除@Qualifier

回答by Shubham Chopra

Try adding @EntityScan(basePackages = "insert package name here") on top of your main class.

尝试在主类的顶部添加 @EntityScan(basePackages = "insert package name here")。

回答by Ricuzzo

That might happen because the pojos you are using lack of the precise constructor the service needs. That is, try to generate all the constructors for the pojo or objects (model object) that your serviceClient uses, so that the client can be instanced correctly. In your case,regenerate the constructors (with arguments)for your client object (taht is your model object).

这可能是因为您使用的 pojo 缺少服务所需的精确构造函数。也就是说,尝试为您的 serviceClient 使用的 pojo 或对象(模型对象)生成所有构造函数,以便客户端可以正确实例化。在您的情况下,为您的客户端对象(这是您的模型对象)重新生成构造函数(带参数)。

回答by oceangs

The application needs to be placed in the same directory as the scanned package:

应用程序需要放在与扫描包相同的目录中:

enter image description here

在此处输入图片说明

回答by Kristóf Dombi

I had the exactly same issue, with a very very long stack trace. At the end of the trace I saw this:

我遇到了完全相同的问题,堆栈跟踪非常长。在跟踪的末尾,我看到了这个:

InvalidQueryException: Keyspace 'mykeyspace' does not exist

InvalidQueryException: Keyspace 'mykeyspace' 不存在

I created the keyspace in cassandra, and solved the problem.

我在 cassandra 中创建了密钥空间,并解决了问题。

CREATE KEYSPACE mykeyspace
  WITH REPLICATION = { 
   'class' : 'SimpleStrategy', 
   'replication_factor' : 1 
  };

回答by Nitish Sharma

I was facing the same issue, and it was, as i missed marking my DAO class with Entity annotations. I tried below and error got resolved.

我遇到了同样的问题,因为我错过了用实体注释标记我的 DAO 类。我在下面尝试并解决了错误。

/**
*`enter code here`
*/
@Entity <-- was missing earlier
    public class Topic {
        @Id  
        String id;
        String name;
        String desc;

    .
    .
    .
    }

回答by Siddaraju Siddappa

Check out the table structure of Client table, if there is a mismatch between table structure in db and the entity, you would get this error..

查看Client表的表结构,如果db中的表结构与实体不匹配,就会出现这个错误..

I had this error which was coming due to datatype mismatch of primary key between db table and the entity ...

我遇到了这个错误,这是由于 db 表和实体之间主键的数据类型不匹配......