簡體   English   中英

自動裝配的bean為空

[英]Autowired bean is null

我已經在Stackoverflow上閱讀了很多關於自動裝配的問題,但我仍然無法理解為什么我的自動裝配不起作用。

我有一個標准的目錄結構:

com.mycompany
  |-controller
  |-service
  |-model

當我從控制器注入服務時,一切正常。 但是,當我嘗試將一個UserDetailService的自定義實現提供給spring安全性時,它會失敗:

@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(參見組件掃描):

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

  <context:component-scan base-package="com.mycompany"/>
  <tx:annotation-driven/>
  <mvc:annotation-driven/>
</beans>

這是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上下文中放置<context:component-scan base-package="com.mycompany"/> ,在這些包上掃描的所有bean都將由DispatcherServlet上下文管理,並且根上下文不可見,一個管理MyCustomUserDetailService bean的人。

DispatcherServlet是根上下文的子項,它允許將根上下文中的核心bean注入到視圖層bean(如控制器)中。 可見性只是一種方式,您不能將DispatcherServlet上下文中的bean注入到根上下文管理的bean中,這就是它在UserController但不在MyCustomUserDetailService

<context:component-scan base-package="com.mycompany"/>標記移動到根上下文(Spring上下文)應該可以解決問題。

暫無
暫無

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

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