UnsatisfiedDependencyException: Error creating bean with name

后端 未结 19 1043
遇见更好的自我
遇见更好的自我 2020-11-30 01:47

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

org.springframework.beans.factory.Unsatisfi

19条回答
  •  猫巷女王i
    2020-11-30 02:19

    The ClientRepository should be annotated with @Repository tag. 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.

    EDIT If adding the @Repository tag doesn't help, then I think that the problem might be now with the ClientService and 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.

    Also, as Bruno mentioned, the @Qualifier is not needed in the ClientController as you only have a single implementation for the service.

    ClientService.java

    @Service
    public interface ClientService {
    
        void addClient(Client client);
    }
    

    ClientServiceImpl.java (option 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)

    @Service
    public class ClientServiceImpl implements ClientService{
    
        @Autowired
        private ClientRepository clientRepository;
    
        @Transactional
        public void addClient(Client client){
            clientRepository.saveAndFlush(client);
        }
    }
    

    ClientController.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";
        }
    }
    

提交回复
热议问题