简体   繁体   中英

How to fix “Application failed to start” in spring boot and it asks for a bean to be defined

My Spring boot app runs but says failed to start and it says the following:

Field userDetailsService in com.example.security.WebSecurityConfiguration required a bean of type 'com.example.security.UserDetailsServiceImpl' that could not be found.

The injection point has the following annotations:

  • @org.springframework.beans.factory.annotation.Autowired(required=true)

Consider defining a bean of type 'com.example.security.UserDetailsServiceImpl' in your configuration.

I have tried adding @Bean and @Service annotations in my UserDetailsServiceImpl class and adding the beanutils dependency in the pom.xml file but it still issues the same message of failing to start.

My UserDetailsServiceImpl class:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.example.domain.User;
import com.example.repository.UserRepository;

public class UserDetailsServiceImpl implements UserDetailsService{

    @Autowired
    private UserRepository userRepo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userRepo.findByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException("User with username: " + username + " not found");

        }
        return new CustomSpringUser (user); 
    }
}

It should say something like successfully ran Spring-Boot app.

BeanUtils won't help you in this case. The UserDetailsService cannot be properly injected since it is not registered as a bean, which only the following annotations are suitable to do so:

  • @Repository , @Service , @Controller or @Component where I highly recommend @Service in this case.

The annotation must be placed on the class level since you want to inject its instance. Of course, the class must be an implementation of the interface that is the implementation injected in.

@Service // must be on the class level
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // method implementation...
    }
}

On top of that, I recommend you to read the following links:

将@Service批注放在UserDetailsS​​erviceImpl类上。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM