【问题标题】:Spring MVC+Hibernate deployment error : expected at least 1 bean which qualifies as autowire candidate for this dependencySpring MVC+Hibernate 部署错误:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者
【发布时间】:2014-08-19 16:14:44
【问题描述】:

我是 Spring MVC + Hibernate 世界的新手。我开发了一个带有基于 Java 注释的配置的小型应用程序。我在部署阶段收到以下错误:

FAIL - 在上下文路径 /NioERPJ 部署应用程序,但上下文无法启动

Apache Tomcat 日志显示以下错误:

原因: org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 [com.nej.users.service.MyUserDetailsS​​ervice] 类型的限定 bean 找到依赖项:预计至少有 1 个符合条件的 bean 此依赖项的自动装配候选者。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)}。

我的 UserController.Java 文件如下:

package com.nej.controller;

import java.util.Map;
import com.nej.users.model.User;;
import com.nej.users.service.MyUserDetailsService;
import java.text.DateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
 *
 */
@Controller
@RequestMapping(value = {"/admin/usermgmt"})
public class UserController {
    @Autowired
    private MyUserDetailsService myuserdetailsservice;

    @RequestMapping(value = { "/listUsers","/" })
    public String listUsers(Map<String, Object> map) {
        map.put("user", new User());
        map.put("userList", myuserdetailsservice.listUsers());
        return "/admin/usermgmt";
    }

    @RequestMapping("/get/{username}")
    public String getUser(@PathVariable String username, Map<String, Object> map) {
        User user = myuserdetailsservice.getUser(username);
        map.put("user", user);
        return "/admin/useraddedit";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String saveUser(@ModelAttribute("user") User user,BindingResult result) {
        myuserdetailsservice.saveUser(user);

    /*
    * Note that there is no slash "/" right after
    "redirect:"
    * So, it redirects to the path relative to the current
    path
    */
    return "redirect:admin/usermgmt";
    }

    @RequestMapping("/delete/{username}")
    public String deleteUser(@PathVariable("username") String username) {
        myuserdetailsservice.deleteUser(username);
    /*
    * redirects to the path relative to the current path
    */
    // return "redirect:../listBooks";
    /*
    * Note that there is the slash "/" right after
    "redirect:"
    * So, it redirects to the path relative to the project
    root path
    */
    return "redirect:/admin/usermgmt";
}
}

但是,如果我从

中删除 Autowired
`@Autowired`
`private MyUserDetailsService myuserdetailsservice;`

行,则应用部署成功,但是当应用命中

`map.put("userList", myuserdetailsservice.listUsers()); `        

行,它显示空指针异常。请帮助我消除错误。

我的 MyUserDetailService.java 文件如下:

package com.nej.users.service;

/**
 *
 */

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.nej.users.dao.UserDao;
import com.nej.users.model.UserRole;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    //get user from the database, via Hibernate
    @Autowired
    private UserDao userDao;
    @Transactional(readOnly=true)
    @Override
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
        com.nej.users.model.User user = userDao.findByUserName(username);
        List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());
        return buildUserForAuthentication(user, authorities);
    }
// Converts com.mkyong.users.model.User user to
// org.springframework.security.core.userdetails.User
    private User buildUserForAuthentication(com.nej.users.model.User user, List<GrantedAuthority> authorities) {
        return new User(user.getUsername(), user.getPassword(),
        user.isEnabled(), true, true, true, authorities);
    }
    private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
// Build user's authorities
        for (UserRole userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
    }
    List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
        return Result;
    }


    @Transactional
    public void saveUser(com.nej.users.model.User user) {
        userDao.saveUser(user);
    }

    @Transactional( readOnly = true)
    public List<com.nej.users.model.User> listUsers() {
        return userDao.listUsers();
    }

    @Transactional
    public void deleteUser(String username) {
        userDao.deleteUser(username);
    }

    @Transactional( readOnly = true)
    public com.nej.users.model.User getUser(String username) {
        return userDao.findByUserName(username);
    }
}

感谢您快速准确的回复,按照建议,我在配置文件中添加了对 com.nej.users.service 包的组件扫描,如下所示,但结果相同,我仍然收到相同的错误.

package com.nej.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 *
 */
@Configuration  
@EnableWebMvc  
@ComponentScan(basePackages = {"com.nej.controller", "com.nej.users.service"})
public class WebAppConfig extends WebMvcConfigurerAdapter {  

        @Override  
        public void addResourceHandlers(ResourceHandlerRegistry registry) {  
                registry.addResourceHandler("/resources/**").addResourceLocations("/resources/mytheme/");  
        }

}

请帮我解决错误。

我在UserController.java中把@Autowired注解改成了@Autowired(required=false)

@Autowired(required=false)
private MyUserDetailsService myuserdetailsservice;

然后应用程序部署成功,但是,当我点击

时,我仍然得到空指针分配

map.put("userList", myuserdetailsservice.listUsers());

线。现在,我们可以缩小错误原因的范围吗? PL。建议。

【问题讨论】:

  • 症状说:豆子没有被弹簧接线。由于您的配置看起来正确,我想问题出在 Spring 引导中。您使用web.xml 文件还是WebApplicationInitializer,它们包含什么?

标签: hibernate tomcat spring-mvc


【解决方案1】:

问题是 MyUserDetailsService 没有被 Spring 拾取。您需要将com.nej.users.service 添加到您的组件扫描中。如果您使用 Java 配置,则使用注释添加它:

@ComponentScan("com.nej.users.service")

或者如果你使用 XML 配置:

<context:component-scan base-package="com.nej.users.service"/>

您在删除@Autowired 注释时体验到的NullPointerException 很容易理解。由于声明的MyUserDetailsService myuserdetailsservice 字段将是null,因为它从未被初始化。因此,尝试调用 myuserdetailsservice.listUsers() 将引发 NPE。

【讨论】:

  • 我已经执行了这个建议,但是我仍然收到同样的错误,请查看我上传的配置文件。
  • 请提出一些替代方案,因为我仍然无法解决错误。
  • 对不起,我没有更多的建议。看来您的配置正确。否则,这只是通常的嫌疑人,仔细检查拼写错误(我相信你已经有),确保包含你的配置文件(如果你的项目有多个配置),重新编译整个项目(如果MyUserDetailsServiceUserControllerWebAppConfig 位于不同的子项目等中,则尤其重要。
  • 谢谢。我会再检查一遍
  • 我已经制作了@Autowired(required=false) 现在项目部署成功,但是,我仍然在同一行接收NPE。这有助于缩小错误范围吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-24
  • 2015-03-21
  • 2012-11-02
  • 2014-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多