Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 自动连线bean为空_Java_Spring_Spring Security - Fatal编程技术网

Java 自动连线bean为空

Java 自动连线bean为空,java,spring,spring-security,Java,Spring,Spring Security,我已经读了很多关于Stackoverflow上自动布线的问题,但我仍然不明白为什么我的自动布线不起作用 我有一个标准的目录结构: com.mycompany |-controller |-service |-model 当我从控制器注入服务时,一切正常。但是,当我尝试将UserDetailService的自定义实现提供给spring security时,它失败了: @Service public class MyCustomUserDetailService implements

我已经读了很多关于Stackoverflow上自动布线的问题,但我仍然不明白为什么我的自动布线不起作用

我有一个标准的目录结构:

com.mycompany
  |-controller
  |-service
  |-model
当我从控制器注入服务时,一切正常。但是,当我尝试将
UserDetailService
的自定义实现提供给spring security时,它失败了:

@Service
public class MyCustomUserDetailService implements UserDetailsService {

  @Autowired
  private UserService userService; //This attribute remains null

  @Override
  public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    try {
      User userByEmail = userService.findUserByEmail(email); //NullPointerException
      return new UserDetailsAdapter(userByEmail);
    } catch(NoResultException e) {
      return null;
    }
  }
}
UserService
是一项非常简单的服务,由
@Service
组成:

import org.springframework.stereotype.Service;

@Service
public class UserService {
  [...]
}
注意:当从UserController实例化时,UserService已正确自动连接:

@RestController
@RequestMapping("/user")
public class UserController {

  @Autowired
  private UserService service; //This one works!
以下是dispatcher-servlet.xml(请参阅组件扫描):


以下是Spring上下文的相关部分:

<beans:bean id="customUserDetailService" class="com.mycompany.service.customUserDetailService"/>

<authentication-manager>
  <authentication-provider user-service-ref="customUserDetailService">
  </authentication-provider>
</authentication-manager>


有什么想法吗?

我很确定您的问题与以下事实有关:您的bean是由
DispatcherServlet
上下文而不是根上下文管理的。通过将
放在
DispatcherServlet
上下文中,这些包上扫描的所有bean都将由
DispatcherServlet
上下文管理,并且根上下文(管理
MyCustomUserDetailService
bean的根上下文)不可见

DispatcherServlet
是根上下文的子级,它允许将根上下文中的核心bean注入视图层bean(如控制器)。可见性只是一种方式,您不能将来自
DispatcherServlet
上下文的bean注入到由根上下文管理的bean中,这就是为什么它在
UserController
中工作,但在
MyCustomUserDetailService
中不工作

标记移动到根上下文(Spring上下文)应该可以做到这一点

<beans:bean id="customUserDetailService" class="com.mycompany.service.customUserDetailService"/>

<authentication-manager>
  <authentication-provider user-service-ref="customUserDetailService">
  </authentication-provider>
</authentication-manager>