[java] UnsatisfiedDependencyException: Error creating bean with name

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

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)}

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)}

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.

This question is related to java spring spring-mvc

The answer is


Add @Component annotation just above the component definition


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

You will need a @Repository on your ClientRepository implementation 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.

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

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

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


I know it seems too late, but it may help others in future.

I face the same error and the problem was that spring boot did not read my services package so add:

@ComponentScan(basePackages = {"com.example.demo.Services"}) (you have to specify your own path to the services package) and in the class demoApplication (class that have main function) and for service interface must be annotated @Service and the class that implement the service interface must be annotated with @Component, then autowired the service interface.


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

enter image description here


If you describe a field as criteria in method definition ("findBy"), You must pass that parameter to the method, otherwise you will get "Unsatisfied dependency expressed through method parameter" exception.

public interface ClientRepository extends JpaRepository<Client, Integer> {
       Client findByClientId();                ////WRONG !!!!
       Client findByClientId(int clientId);    /// CORRECT 
}

*I assume that your Client entity has clientId attribute.


I just added the @Repository annotation to Repository interface and @EnableJpaRepositories ("domain.repositroy-package") to the main class. It worked just fine.


That was the version incompatibility where their was the inclusion of lettuce. When i excluded , it worked for me.

<!--Spring-Boot 2.0.0 -->
    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <exclusions>
                    <exclusion>
                        <groupId>io.lettuce</groupId>
                        <artifactId>lettuce-core</artifactId>
                    </exclusion>
                </exclusions>    
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
            </dependency>

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


There is another instance still same error will shown after you doing everything above mentioned. When you change your codes accordingly mentioned solutions make sure to keep originals. So you can easily go back. So go and again check dispatcher-servelet configuration file's base package location. Is it scanning all relevant packages when you running application.

<context:component-scan base-package="your.pakage.path.here"/>

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.

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

    .
    .
    .
    }

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..

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


Add @Repository annotation to the Spring Data JPA repo


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

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

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

If you are using Spring Boot, your main app should be like this (just to make and understand things in simple way) -

package aaa.bbb.ccc;
@SpringBootApplication
@ComponentScan({ "aaa.bbb.ccc.*" })
public class Application {
.....

Make sure you have @Repository and @Service appropriately annotated.

Make sure all your packages fall under - aaa.bbb.ccc.*

In most cases this setup resolves these kind of trivial issues. Here is a full blown example. Hope it helps.


Just add @Service annotation to top of the service class


This error can occur if there are syntax errors with Derived Query Methods. For example, if there are some mismatches with entity class fields and the Derived methods' names.


According to documentation you should set XML configuration:

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

See if your <context:component-scan base-package="your package "/> is missing in either config or context xml file


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).


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)