@Autowired对象在一个类中获取空值,而在另一个类中成功连接

时间:2011-05-07 14:36:02

标签: spring spring-mvc autowired

我正在使用Spring 3和Spring Security开发一个项目。我的问题是IoC容器。当我为Spring Security-3编写自己的UserDetailsService实现时,问题就出现了。我检查了其他问题,但仍无法解决问题。

问题的定义是:

我有两个单独的类(一个UsersController.java扩展@ControllerProjectUserDetailsService扩展@Service,它使用一个公共对象进行自动装配。但是,虽然对象在UsersController中成功自动装配,但null类中的ProjectUserDetailsService已成功创建此类(ProjectUserDetailsService)的对象(我通过调试验证了这一点)

有任何建议如何解决这个问题?

以下是我的web.xmlproject-servlet.xmlproject-security.xml文件及相关课程。

Web.xml`

<?xml version="1.0" encoding="UTF-8"?>
<!--
  - Tutorial web application
  -
  -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>Ecognitio with Spring Security</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
            /WEB-INF/ecognitio-servlet.xml
            /WEB-INF/ecognitio-security.xml
        </param-value>
  </context-param>
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>tutorial.root</param-value>
  </context-param>
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
  </listener>
  <servlet>
    <servlet-name>ecognitio</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>project</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>project</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

project-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.project" />

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

     <bean  id="messageSource" 
            class="org.springframework.context.support.ResourceBundleMessageSource"
            p:basename="Messages"/>

  <!-- misc -->
<!--    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="suffix" value=".jsp"/>
    </bean>  --> 


    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">

       <property name="viewClass">
         <value>
              org.springframework.web.servlet.view.tiles2.TilesView
            </value>
        </property>
    </bean>

    <bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
      <property name="definitions">
             <list>
                <value>/WEB-INF/tiles.xml</value>
             </list>
      </property>
    </bean>

    <!-- Configures Hibernate - Database Config -->
    <import resource="db-config.xml" />
</beans>

project-security.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
  - Sample namespace-based configuration
  -
  -->

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

    <debug />

    <global-method-security pre-post-annotations="enabled">
        <!-- AspectJ pointcut expression that locates our "post" method and applies security that way
        <protect-pointcut expression="execution(* bigbank.*Service.post*(..))" access="ROLE_TELLER"/>
        -->
    </global-method-security>

    <http pattern="/loggedout.jsp" security="none"/>

    <http use-expressions="true" >
        <intercept-url pattern="/secure/extreme/**" access="hasRole('ROLE_SUPERVISOR')"/>
        <intercept-url pattern="/secure/**" access="isAuthenticated()" />

        <!--
             Allow all other requests. In a real application you should
             adopt a whitelisting approach where access is not allowed by default
          -->
        <intercept-url pattern="/login.jsp*" access="isAuthenticated()==false"/>
        <intercept-url pattern="/timeout.jsp*" access="isAuthenticated()==false"/>
        <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />

       <!-- <intercept-url pattern="/**" access="permitAll" /> --> 
        <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" default-target-url="/dashboard.html" />
        <logout logout-success-url="/login.jsp" delete-cookies="JSESSIONID"/>
        <remember-me />
<!--
    Uncomment to enable X509 client authentication support
        <x509 />
-->
        <!-- Uncomment to limit the number of sessions a user can have 
        <session-management invalid-session-url="/login.jsp">
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
        </session-management>
        -->

    </http>

            <!-- HERE IS WHERE I USE an object of ProjectUserDetailsService -->
    <authentication-manager>
         <authentication-provider user-service-ref="userDetailsService" />   
    </authentication-manager>


 <!--  

</beans:beans>

UsersController.java(此类的UsersDAO类对象的自动装配成功)

package com.project.users;

//required imports



@Controller
public class UsersControllers
{

@Autowired
private UsersDAO usersDAO;

    //Some more autowires and some class specific code


}

ProjectUserDetailsService.java(用户DAO的自动装配不起作用)

package com.project.security;

import java.util.ArrayList;
import java.util.Collection;

//required imports


@SuppressWarnings("deprecation")
@Service("userDetailsService") 
public class ProjectUserDetailsService implements UserDetailsService {

   @Autowired
   private UsersDAO usersDAO;
  @Autowired private Assembler assembler;

  @Transactional(readOnly = true)
  public UserDetails loadUserByUsername(String username)
      throws UsernameNotFoundException, DataAccessException {

    UserDetails userDetails = null;
    //For debugging purposes
    if(usersDAO==null){
        System.out.println("DAO IS NULL");
        System.out.println("DAO IS NULL");
        System.out.println("DAO IS NULL");

    }
    User userEntity = usersDAO.findUserbyEmail("'"+username+"'");


    if (userEntity == null)
      throw new UsernameNotFoundException("user not found");

    return assembler.buildUserFromUserEntity(userEntity);

  }
}

5 个答案:

答案 0 :(得分:4)

是的,似乎不可能将对象自动装入从spring安全类继承的bean中。我不知道这是否是春季安全方面的错误,或者是否为安全性做了什么。如果有人有解释我会有兴趣听到它。您可以通过xml配置手动注入bean(而不是使用@Autowired注释)来解决您的问题,然后它们就会出现。但是要注意一点......

我这样做了,我注意到我的userDao上有注释(特别是@Transactional)不再在事务中运行。我的userDao被用于多个地方。如果我将它注入我的自定义AbstractUserDetailsAuthenticationProvider,它不再在任何其他使用它的类的事务中操作。将注入删除到自定义的AbstractUserDetailsAuthenticationProvider中,当其他正在接收它的对象(通过@Autowired或手动xml注入)使用时,将事务功能恢复到我的userDao。

那么我如何将我的userDao引入我的Spring Security上下文并仍保留@Transactional?我必须创建一个Factory类:

public class UserDaoFactory {

private static UserDao userDao;

public static UserDao getUserDao() {
    return UserDaoFactory.userDao;
}

public void setUserDao(UserDao userDao) {
    UserDaoFactory.userDao = userDao;
}
}

然后将此和你的dao两个对象放入弹簧容器中:

<bean id="userDao" class="com.package.UserDaoImpl">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="userDaoFactory" class="com.package.UserDaoFactory">
    <property name="userDao" ref="userDao" />
</bean>

因此userDao将自动装入您的userDaoFactory。它将拥有它所有的@Transactional功能(因为Spring安全性没有剥离它?)。然后在你的spring安全对象中你可以做一个:

userDao = UserDaoFactory.getUserDao();

我在我的自定义AbstractUserDetailsAuthenticationProvider对象中实现了ServletContextAware,以便在初始化期间执行上述操作,并使用中提琴。

请注意,虽然您可以通过xml配置将bean手动注入spring安全对象以克服@Autowired问题,但如果您尝试将该DAO包装在@Transactional中,则最终会遇到新问题。

现在也许有人知道为什么会这样。这可能是我的错误配置(我承认我不是春天专家),或者它可能是春天的特征。我很想听听别人有什么要说的,以及如何改善这一点。

答案 1 :(得分:1)

由于第二个bean不在project-servlet.xml中指定的指定bean注释包组件扫描中:

<context:component-scan base-package="com.project" />

它不认为它是一项服务,也不会翻译注释。

您需要进一步扩展它或将其移动到以com.project开头的包中,或者像这样:

<context:component-scan base-package="com" />

答案 2 :(得分:1)

我不知道为什么:(但是从project-security.xml中删除标签并且可以正常工作!

http://forum.springsource.org/showthread.php?115561-Autowire-on-custom-authentication-provider-doesn-t-work

答案 3 :(得分:0)

这可能是由于SEC-1911导致在依赖像AutowiredAnnotationBeanPostProcessor之类的BeanPostProcessors并使用<debug />元素时导致问题。尝试删除<debug />并查看@Autowired是否再次有效。请注意,第一个问题是SEC-1885的副本,这是修复的地方,但第一个问题的症状更符合此问题。

答案 4 :(得分:-2)

我遇到了同样的问题。虽然这可以通过多种方式实现,但就我而言,我创建了一个新对象,而不是使用autowired。即:

private Service service = new ServiceImpl();

而不是:

@Autowired private Service service;

这不是使用存储库注入的服务,而是在控制器之上。