簡體   English   中英

如何在春季啟動中修復“應用程序啟動失敗”,並要求定義一個bean

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

我的Spring引導應用程序運行但顯示無法啟動,並顯示以下內容:

com.example.security.WebSecurityConfiguration中的字段userDetailsS​​ervice需要一個類型為com.example.security.UserDetailsS​​erviceImpl的bean。

注入點具有以下注釋:

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

考慮在配置中定義類型為“ com.example.security.UserDetailsS​​erviceImpl”的bean。

我嘗試在UserDetailsS​​erviceImpl類中添加@Bean@Service批注,並在pom.xml文件中添加beanutils依賴項,但它仍然會發出相同的消息,提示無法啟動。

我的UserDetailsServiceImpl類:

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

它應該說像成功運行Spring-Boot應用程序。

在這種情況下,BeanUtils不會為您提供幫助。 由於UserDetailsService尚未注冊為Bean,因此無法正確注入,只有以下注釋才適合:

  • @Repository@Service @Repository@Service @Controller@Component在這種情況下,我強烈建議使用@Service

由於要注入其實例,因此必須將其置於類級別 當然,該類必須是接口的實現,即已注入的實現。

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

最重要的是,我建議您閱讀以下鏈接:

將@Service批注放在UserDetailsS​​erviceImpl類上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM