【问题标题】:UserDetailsService implemented class is not injecting autowired fieldUserDetailsS​​ervice 实现的类未注入自动装配字段
【发布时间】:2014-03-04 06:48:39
【问题描述】:

我正在使用 acegi 身份验证进行登录。当我尝试比较来自 databade 的值时 我正在使用以下课程

 @Transactional(readOnly = true)
    @Service
    public class CustomUserDetailsService implements UserDetailsService {
        @Autowired
        private UserDAO userdao;
    public UserDetails loadUserByUsername(String username)
                throws UsernameNotFoundException, DataAccessException {
com.quest.model.dto.User dbUser = userdao.searchDatabase(username);
    }
    }

但自动装配字段未初始化。 但它在控制器类中初始化。 这个类是通过spring-security 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:security="http://www.springframework.org/schema/security"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/security 
                http://www.springframework.org/schema/security/spring-security.xsd
                http://www.springframework.org/schema/mvc 
                http://www.springframework.org/schema/mvc/spring-mvc.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

        <!-- This is where we configure Spring-Security  -->
        <!-- <context:annotation-config />
        <context:component-scan base-package="com.quest" /> 
        <mvc:annotation-driven /> --> 
        <security:http auto-config="true" use-expressions="true" access-denied-page="/auth/denied" >

            <security:intercept-url pattern="/auth/home" access="permitAll"/>
            <security:intercept-url pattern="/admin/*" access="hasRole('ROLE_ADMIN')"/>
            <security:intercept-url pattern="/student/*" access="hasRole('ROLE_STUDENT')"/>
            <security:intercept-url pattern="/control/*" access="hasRole('ROLE_TEACHER')"/>

            <!-- <security:form-login
                    login-page="/auth/home" 
                    authentication-failure-url="/auth/home?error=true" 
                    default-target-url="/control/dummyLogin"/> -->
            <security:form-login
                    login-page="/auth/home" 
                    authentication-failure-url="/auth/home?error=true" 
                    default-target-url="/student/student"/>

            <security:logout 
                    invalidate-session="true" 
                    logout-success-url="/auth/home" 
                    logout-url="/student/logout"/>

        </security:http>

        <!-- Declare an authentication-manager to use a custom userDetailsService -->
        <security:authentication-manager>
                <security:authentication-provider user-service-ref="customUserDetailsService">
                        <security:password-encoder ref="passwordEncoder"/>
                </security:authentication-provider>
        </security:authentication-manager>

        <!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
        <bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>

        <!-- A custom service where Spring will retrieve users and their corresponding access levels  -->
        <bean id="customUserDetailsService" class="com.quest.service.CustomUserDetailsService"/>


    </beans>

这是 spring-servlrt.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:ws="http://jax-ws.dev.java.net/spring/core"   
    xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"   
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://jax-ws.dev.java.net/spring/core http://jax-ws.java.net/spring/core.xsd
        http://jax-ws.dev.java.net/spring/servlet http://jax-ws.java.net/spring/servlet.xsd">


    <context:annotation-config />
    <context:component-scan base-package="com.quest.*" />   
    <mvc:annotation-driven /> 
    <bean class="org.springframework.remoting.jaxws.SimpleJaxWsServiceExporter">
      <property name="baseAddress" value="http://localhost:9999/"/>
    </bean>

    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <value>com.quest.model.dto</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.configurationClass">org.hibernate.cfg.AnnotationConfiguration</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven />

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager" depends-on="sessionFactory">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

<!--    <bean id="jacksonMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> !-->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter" />
            </list>
        </property>
    </bean>


     <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="com.quest.data.converter.HibernateAwareObjectMapper" />
                </property>
            </bean>

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="200000" />
    </bean>

    <bean id="seedDataInstaller" 
        class="com.quest.model.SeedData"  init-method="populateSeed">
    </bean>

</beans>

userDAO 看起来像

package com.quest.model.dao; @Repository("userdao") public class UserDAO { ...}

【问题讨论】:

  • 你在哪里使用CustomUserDetailsService bean?
  • 向我们展示您的 xml。您正在扫描注释吗?
  • 在 spring-security xml 中我已将其映射为
  • 你想在任何地方使用它吗?你有什么证据表明the autowired field is not initializing.?如果找不到 bean,Spring 将因异常而失败。它不会离开它null
  • 你在混合xml和注解,如果你想让你的bean来自xml,你需要设置属性userdao

标签: java spring spring-annotations


【解决方案1】:

没有定义名为“userdao”的bean

您必须在 xml 配置中将 UserDao 定义为 bean 或使用 @component 注释 UserDao 类

如果您遵循基于注释的配置,请在您的配置 xml 中取消注释以下部分

<!-- 
<context:annotation-config />
<context:component-scan base-package="com.quest.*>" /> 
<mvc:annotation-driven /> 
--> 

【讨论】:

  • 你能告诉我你的配置文件和 UserDao 类吗?
  • @Akhil 请将您的组件扫描基础包值更改为 com.quest。*
  • 抱歉还是有同样的问题
  • 哦!请发布 spring-servlet.xml 和 UserDao 类
【解决方案2】:

您的 web.xml 正在创建两个 Spring 应用程序上下文。我们称它们为 Security(在 spring-security.xml 之后)和 Servlet(在 spring-servlet.xml 之后)。安全性由 ContextLoaderListener 监听器创建,而 Servlet 由 DispatcherServlet servlet 创建。安全性是 Servlet 的父级。也就是说Security中的bean只对Security中的其他bean可见,而Servlet中的bean既可以看到Security中的bean,也可以看到Servlet中的bean。

您在 Security 中定义 CustomUserDetailsS​​ervice (CUDS) bean,在 Servlet 中定义 UserAccountDao 和 UserDao bean,因此 CUDS bean 看不到它们。

【讨论】:

  • 这很好地说明了问题的背景。您能否扩展您的答案以包括有关如何实际解决问题的具体步骤?
【解决方案3】:

我通过在 spring 配置文件中添加 UserDAO 解决了这个问题

<bean id="userDAOImpl" class="com.qvantel.dao.UserDAOImpl"/>

签入db-config.xml

我的配置文件

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

  <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>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml, /WEB-INF/spring/appServlet/db-config.xml, /WEB-INF/spring/appServlet/spring-security.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>QRTServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/appServlet/webconfig-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>QRTServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <session-config>
        <session-timeout>60</session-timeout>
    </session-config>

</web-app>

webconfig-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee https://www.springframework.org/schema/jee/spring-jee-4.0.xsd">

    <mvc:annotation-driven conversion-service="conversionService" />
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean" >
        <property name="converters">
            <set>
                <bean class="com.qvantel.conveter.JobConverter"/>
                <!-- 
                add all the converters here
                <bean class="com......Converter"/> -->
            </set>
        </property>
    </bean>
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <context:component-scan base-package="com.qvantel.web" />
    <!-- <context:component-scan base-package="com.qvantel.web" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan> -->
    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- max upload size in bytes -->
        <property name="maxUploadSize" value="20971520" /> <!-- 20MB -->

        <!-- max size of file in memory (in bytes) -->
        <property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
    </bean>

     <!-- Tiles configuration -->

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

db-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee https://www.springframework.org/schema/jee/spring-jee-4.0.xsd">

    <context:component-scan base-package="com.qvantel.dao, com.qvantel.service" />
    <!-- <context:component-scan base-package="com.qvantel">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="regex" expression="com.qvantel.*"/>
    </context:component-scan> -->
     <jee:jndi-lookup id="qvantelDataSource" expected-type="javax.sql.DataSource" jndi-name="jdbc/Qvantel_DB" /> 

     <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="qvantelDataSource" />
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.qvantel.model.User</value>
                <value>com.qvantel.model.Candidate</value>
                <value>com.qvantel.model.Job</value>
                <value>com.qvantel.model.ProfilesScreened</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">false</prop>
            </props>
        </property>
    </bean>
    <tx:annotation-driven />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean id="userDAOImpl" class="com.qvantel.dao.UserDAOImpl"/>
</beans>

spring-security.xml

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

    <!-- <context:component-scan base-package="com.qvantel" />   -->
    <security:http auto-config="true" use-expressions="true" >
        <security:intercept-url pattern="/" access="permitAll" />
        <security:intercept-url pattern="/viewJobs" access="hasRole('ADMIN')" />
        <security:intercept-url pattern="/viewCandidates" access="hasRole('ADMIN')" />
        <!-- <intercept-url pattern="/home" access="permitAll" />
        <intercept-url pattern="/admin**" access="hasRole('ADMIN')" />
        <intercept-url pattern="/dba**" access="hasRole('ADMIN') and hasRole('DBA')" /> -->
        <security:form-login  login-page="/login"
                     login-processing-url="/login"
                     default-target-url="/home"
                     authentication-failure-url="/login?error"
                     username-parameter="userName"
                     password-parameter="password" />
        <security:logout logout-success-url="/login?logout" logout-url="/j_spring_security_logout" />
        <security:csrf disabled="true"/>
    </security:http>

    <security:authentication-manager >
        <security:authentication-provider user-service-ref="customUserDetailsService">
           <!-- <security:password-encoder ref="bcryptEncoder"/> -->
           <security:password-encoder hash="bcrypt" />
        </security:authentication-provider>   
    </security:authentication-manager>

    <beans:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />  
    <beans:bean id="customUserDetailsService" class="com.qvantel.service.CustomUserDetailsService" />

</beans:beans>

在 DAOImpl 类上使用 @Repository,在服务类上使用 @Service,在控制器类上使用 @Controller

在所有需要的 DAOImpl 方法中使用 @Transactional

【讨论】:

    猜你喜欢
    • 2013-05-12
    • 2014-08-22
    • 2016-03-29
    • 1970-01-01
    • 2015-09-14
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    相关资源
    最近更新 更多