【问题标题】:Spring autowire byName giving NullPointer exceptionSpring autowire byName 给出 NullPointer 异常
【发布时间】:2017-11-30 01:00:38
【问题描述】:

我正在尝试将 Apache Shiro 集成到我的 Spring Web MVC 项目中,但在适当的 bean 定义方面存在问题。这是我的 applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">       

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>/WEB-INF/jdbc.properties</value>    
                <value>/WEB-INF/wmsauth.properties</value>  
            </list>    
        </property>               
    </bean>         

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>      

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>  
        <property name="packagesToScan" value="com.smth.smth.model"/>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>     
    </bean> 

    <bean id="shiroFilter" class=  "org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>   
        <property name="loginUrl" value="/login.jsp"/>
        <property name="successUrl" value="/login/index"/>         
        <property name="filterChainDefinitions">
            <value>
                /login.jsp = authc                  
                /login/** = authc   
                /admin/** = authc
                /logout.htm = logout  
            </value>
        </property>
    </bean>          

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">            
        <property name="realm" ref="adminRealm"/>
        <property name="cacheManager" ref="cacheManager"/>   

    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> 

    <bean id="adminRealm" class="com.smth.smth.model.admin.AdminRealm" autowire="byName">          
        <property name="credentialsMatcher" ref = "sha256Matcher"/>
        <property name="authenticationQuery" value = "SELECT password, salt FROM admin WHERE email = ?"/>
        <property name="permissionsLookupEnabled" value = "true"/>
        <property name="userRolesQuery" value = "SELECT role_name FROM admin_role WHERE email = ?"/>
        <property name="permissionsQuery" value = "SELECT permission FROM roles_permission WHERE role_name = ?"/>
        <property name="dataSource" ref = "dataSource"/>       
    </bean>  

    <bean id="sha256Matcher" class="org.apache.shiro.authc.credential.Sha256CredentialsMatcher" >
        <property name="storedCredentialsHexEncoded" value = "false"/>
        <property name="hashIterations" value = "1024"/>
    </bean> 

    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" /> 

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

如您所见,我在这里定义了adminRealm bean,并使用autowire = "byName"

AdminRealm类如下:

package com.smth.smth.model.admin;

import com.smth.smth.service.AdminService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SaltedAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.springframework.beans.factory.annotation.Autowired;

public class AdminRealm extends JdbcRealm {

    @Autowired
    AdminService adminService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {     
        UsernamePasswordToken userPassToken = (UsernamePasswordToken) token;
        final String username = userPassToken.getUsername();

        if (username == null) {
            System.out.println("Username is null.");
            return null;
        }            
        final Admin admin = adminService.getByEmail(username);

        if (admin == null) {
            System.out.println("User does not exist with principal: [" + username + "]");
            return null;
        }
            SaltedAuthenticationInfo info = new AdminAuthInfo(username, admin.getPassword(), admin.getSalt());

        return info;
    }
}

这里有AdminService,即@Autowired,我希望通过applicationContext.xml中的配置由Spring依赖注入处理,但我一直在@987654329收到java.lang.NullPointerException @。任何信息将不胜感激。

我认为组件扫描应该没有问题。我的dispatcher-servlet如下:

    <?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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.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">

    <context:component-scan base-package="com.smth.smth"/>
    <mvc:resources mapping="/resources/**" location="/resources/" />
    <mvc:annotation-driven/>        

    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />

</beans>

【问题讨论】:

    标签: spring-mvc dependency-injection autowired shiro applicationcontext


    【解决方案1】:

    您有 adminService 设置器吗?如果没有,请添加setAdminService() 并重试。

    这是参考: Spring Reference - Autowiring collaborators

    例如,如果一个 bean 定义设置为按名称自动装配,并且它包含一个主 属性(也就是说,它有一个 setMaster(..) 方法),Spring 寻找一个 bean 定义命名为 master,并使用它来设置属性。

    【讨论】:

    • 请将答案的关键部分粘贴在这里。
    【解决方案2】:

    您的 AdminService bean 未在 spring 上下文中注册。尝试在 context.xml 中添加或通过注解声明。

    【讨论】:

    • 我已经通过注释声明了它,并且可以与其他控制器类一起正常工作。
    猜你喜欢
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多