[英]How to fix “Application failed to start” in spring boot and it asks for a bean to be defined
我的Spring引導應用程序運行但顯示無法啟動,並顯示以下內容:
com.example.security.WebSecurityConfiguration中的字段userDetailsService需要一個類型為com.example.security.UserDetailsServiceImpl的bean。
注入點具有以下注釋:
@org.springframework.beans.factory.annotation.Autowired(required=true)
考慮在配置中定義類型為“ com.example.security.UserDetailsServiceImpl”的bean。
我嘗試在UserDetailsServiceImpl類中添加@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批注放在UserDetailsServiceImpl類上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.