Error creating bean in dependency injection with spring-boot

Here is my code - https://github.com/iyngaran/to-do-list

I have UserRepository class in info.iyngaran.core.auth.repository package and it is annotated with @Repository.

When I try to inject it in CustomUserDetailsService class which is in info.iyngaran.core.auth.security package, I am getting the following error.

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

Can somebody help me to find out the issue on this ? Thanks in advance.

Upvotes: 0

Views: 1193

Answers (2)

I fixed the issue by adding the following line to the spring boot main class.

@EnableJpaRepositories({"info.iyngaran.core","info.iyngaran.todolistapi"})

and that resolved my issue. Here is the details - https://stackoverflow.com/a/53172477/9348637

Upvotes: 1

LynAs
LynAs

Reputation: 6567

The main problem is component scanning. So arrange your code following way

Move your TodolistApiApplication class at the package root info.iyngaran

and clear the clutter

package info.iyngaran;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import java.util.TimeZone;

@SpringBootApplication
public class TodolistApiApplication {

    @PostConstruct
    void init() {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }


    public static void main(String[] args) {
        SpringApplication.run(TodolistApiApplication.class, args);
    }

}

also use constructor injection (not mandatory for the fix). field injection is very bad practice

private final UserRepository userRepository;

public CustomUserDetailsService(UserRepository userRepository) {
    this.userRepository = userRepository;
}

Upvotes: 0

Related Questions