Troyturk的gravatar头像
Troyturk 2015-11-23 17:35:56

spring配置shiro为什么报错Error creating bean with name?

启动的时候就报错

部分错误信息:

1org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shiroFilter' defined in class path resource [spring-shiro-web.xml]: Cannot resolve reference to bean 'securityManager' while setting bean property 'securityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityManager' defined in class path resource [spring-shiro-web.xml]: Cannot resolve reference to bean 'userRealm' while setting bean property 'realm'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRealm' defined in class path resource [spring-shiro-web.xml]: Cannot resolve reference to bean 'userService' while setting bean property 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userService' is defined

 

spring-shiro-web.xml是这样的:

001<?xml version="1.0" encoding="UTF-8"?>
003       xmlns:util="http://www.springframework.org/schema/util"
004       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
005       xsi:schemaLocation="
006       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
007       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
008 
009    <!-- 缓存管理器 使用Ehcache实现 -->
010    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
011        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
012    </bean>
013 
014    <!-- 凭证匹配器 -->
015    <bean id="credentialsMatcher" class="com.moon.credentials.RetryLimitHashedCredentialsMatcher">
016        <constructor-arg ref="cacheManager"/>
017        <property name="hashAlgorithmName" value="md5"/>
018        <property name="hashIterations" value="2"/>
019        <property name="storedCredentialsHexEncoded" value="true"/>
020    </bean>
021 
022    <!-- Realm实现 -->
023    <bean id="userRealm" class="com.moon.service.realm.UserRealm">
024        <property name="userService" ref="userService"/>
025        <property name="credentialsMatcher" ref="credentialsMatcher"/>
026        <property name="cachingEnabled" value="true"/>
027        <property name="authenticationCachingEnabled" value="true"/>
028        <property name="authenticationCacheName" value="authenticationCache"/>
029        <property name="authorizationCachingEnabled" value="true"/>
030        <property name="authorizationCacheName" value="authorizationCache"/>
031    </bean>
032 
033    <!-- 会话ID生成器 -->
034    <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>
035 
036    <!-- 会话Cookie模板 -->
037    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
038        <constructor-arg value="sid"/>
039        <property name="httpOnly" value="true"/>
040        <property name="maxAge" value="180000"/>
041    </bean>
042 
043    <!-- 会话DAO -->
044    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
045        <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
046        <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
047    </bean>
048 
049    <!-- 会话验证调度器 -->
050    <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
051        <property name="sessionValidationInterval" value="1800000"/>
052        <property name="sessionManager" ref="sessionManager"/>
053    </bean>
054 
055    <!-- 会话管理器 -->
056    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
057        <property name="globalSessionTimeout" value="1800000"/>
058        <property name="deleteInvalidSessions" value="true"/>
059        <property name="sessionValidationSchedulerEnabled" value="true"/>
060        <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
061        <property name="sessionDAO" ref="sessionDAO"/>
062        <property name="sessionIdCookieEnabled" value="true"/>
063        <property name="sessionIdCookie" ref="sessionIdCookie"/>
064    </bean>
065 
066    <!-- 安全管理器 -->
067    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
068        <property name="realm" ref="userRealm"/>
069        <property name="sessionManager" ref="sessionManager"/>
070        <property name="cacheManager" ref="cacheManager"/>
071    </bean>
072 
073    <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
074    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
075        <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
076        <property name="arguments" ref="securityManager"/>
077    </bean>
078 
079    <!-- 基于Form表单的身份验证过滤器 -->
080    <bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
081        <property name="usernameParam" value="username"/>
082        <property name="passwordParam" value="password"/>
083        <property name="loginUrl" value="/login.jsp"/>
084    </bean>
085 
086    <!-- Shiro的Web过滤器 -->
087    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
088        <property name="securityManager" ref="securityManager"/>
089        <property name="loginUrl" value="/login.jsp"/>
090        <property name="unauthorizedUrl" value="/login.jsp"/>
091        <property name="filters">
092            <util:map>
093                <entry key="authc" value-ref="formAuthenticationFilter"/>
094            </util:map>
095        </property>
096        <property name="filterChainDefinitions">
097            <value>
098                /index.jsp = anon
099                 
100                WEB-INF/user/login.jsp = authc
101                /logout = logout
102                /user/** = roles[admin]
103                 
104            </value>
105        </property>
106    </bean>
107 
108    <!-- Shiro生命周期处理器-->
109    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
110 
111</beans>

 

springmvc.xml是这样的:

01<?xml version="1.0" encoding="UTF-8"?>
03       xmlns:context="http://www.springframework.org/schema/context"
04       xmlns:aop="http://www.springframework.org/schema/aop"
05       xmlns:mvc="http://www.springframework.org/schema/mvc"
06       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
07       xsi:schemaLocation="
08       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
09       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
10       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
11       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
12       
13      <mvc:annotation-driven/>
14         
15    <!-- 自动搜索@Controller标注的类 用于指明系统从哪个路径下寻找controller,然后提前初始化这些对象。 -->
16    <context:component-scan base-package="com.moon.web" />
17 
18    <!-- Default ViewResolver -->
19    <bean id="viewResolver"
20        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
21        <property name="viewClass"
22            value="org.springframework.web.servlet.view.JstlView" />
23        <property name="prefix" value="/WEB-INF/" />
24        <property name="suffix" value=".jsp"></property>
25    </bean>
26 
27    <!-- 文件上传 -->
28    <bean id="multipartResolver"
29        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
30        <!-- 设置上传文件的最大尺寸为10MB -->
31        <property name="maxUploadSize" value="104857600"/>
32        <property name="defaultEncoding" value="utf-8" />
33         <property name="maxInMemorySize" value="4096"/>
34    </bean>
35 
36    <!-- 静态文件访问 -->
37    <mvc:default-servlet-handler />
38     
39     <aop:config proxy-target-class="true"></aop:config>
40    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
41        <property name="securityManager" ref="securityManager"/>
42    </bean>
43     
44    <!-- 控制器异常处理 -->
45    <bean id="exceptionHandlerExceptionResolver" class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
46    </bean>
47    <bean class="com.moon.web.exception.DefaultExceptionHandler"/>
48     
49     
50</beans>

 

UserRealm是这样的:

01package com.moon.service.realm;
02 
03import org.apache.shiro.authc.AuthenticationException;
04import org.apache.shiro.authc.AuthenticationInfo;
05import org.apache.shiro.authc.AuthenticationToken;
06import org.apache.shiro.authc.LockedAccountException;
07import org.apache.shiro.authc.SimpleAuthenticationInfo;
08import org.apache.shiro.authc.UnknownAccountException;
09import org.apache.shiro.authz.AuthorizationInfo;
10import org.apache.shiro.authz.SimpleAuthorizationInfo;
11import org.apache.shiro.realm.AuthorizingRealm;
12import org.apache.shiro.subject.PrincipalCollection;
13import org.apache.shiro.util.ByteSource;
14import org.springframework.beans.factory.annotation.Autowired;
15import org.springframework.stereotype.Service;
16 
17import com.moon.entity.User;
18import com.moon.service.UserService;
19 
20 
21public class UserRealm extends AuthorizingRealm {
22 
23    @Autowired
24    private UserService userService;
25 
26    public void setUserService(UserService userService) {
27        this.userService = userService;
28    }
29 
30    //授权实现,获取用户权限的方法
31    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
32        String username = (String)principals.getPrimaryPrincipal();
33 
34        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
35        authorizationInfo.setRoles(userService.findRoles(username));
36        authorizationInfo.setStringPermissions(userService.findPermissions(username));
37 
38        return authorizationInfo;
39    }
40 
41    //认证实现,获取用户信息的方法
42    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
43 
44        String username = (String)token.getPrincipal();
45 
46        User user = userService.findByUsername(username);
47 
48        if(user == null) {
49            throw new UnknownAccountException();//没找到帐号
50        }
51 
52        if(Boolean.TRUE.equals(user.getLocked())) {
53            throw new LockedAccountException(); //帐号锁定
54        }
55 
56        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现
57        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
58                user.getUserName(), //用户名
59                user.getPassword(), //密码
60                ByteSource.Util.bytes(user.getCredentialsSalt()),//salt=username+salt
61                getName()  //realm name
62        );
63        return authenticationInfo;
64    }
65 
66    @Override
67    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
68        super.clearCachedAuthorizationInfo(principals);
69    }
70 
71    @Override
72    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
73        super.clearCachedAuthenticationInfo(principals);
74    }
75 
76    @Override
77    public void clearCache(PrincipalCollection principals) {
78        super.clearCache(principals);
79    }
80 
81    public void clearAllCachedAuthorizationInfo() {
82        getAuthorizationCache().clear();
83    }
84 
85    public void clearAllCachedAuthenticationInfo() {
86        getAuthenticationCache().clear();
87    }
88 
89    public void clearAllCache() {
90        clearAllCachedAuthenticationInfo();
91        clearAllCachedAuthorizationInfo();
92    }
93 
94}

 

web.xml是这样的:

01<?xml version="1.0" encoding="UTF-8"?>
02<web-app
03        xmlns="http://java.sun.com/xml/ns/javaee"
04        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
06        version="3.0"
07        metadata-complete="false">
08  <context-param>
09    <param-name>webAppRootKey</param-name>
10    <param-value>ssm.root</param-value>
11  </context-param>
12  <context-param>
13    <param-name>contextConfigLocation</param-name>
14    <param-value> 
15            classpath*:applicationContext.xml, 
16            classpath:spring-shiro-web.xml
17        </param-value>
18  </context-param>
19  <context-param>
20    <param-name>log4jConfigLocation</param-name>
21    <param-value>/WEB-INF/classes/log4j.properties</param-value>
22  </context-param>
23  <context-param>
24    <param-name>log4jRefreshInterval</param-name>
25    <param-value>60000</param-value>
26  </context-param>
27  <context-param>
28    <param-name>log4jExposeWebAppRoot</param-name>
29    <param-value>false</param-value>
30  </context-param>
31  <listener>
32    <listener-class
33            org.springframework.web.context.ContextLoaderListener 
34        </listener-class>
35  </listener>
36  <listener>
37    <listener-class
38            org.springframework.web.util.Log4jConfigListener 
39       </listener-class>
40  </listener>
41   <!-- shiro 安全过滤器 -->
42    <!-- The filter-name matches name of a 'shiroFilter' bean inside applicationContext.xml -->
43    <filter>
44        <filter-name>shiroFilter</filter-name>
45        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
46        <async-supported>true</async-supported>
47        <init-param>
48            <param-name>targetFilterLifecycle</param-name>
49            <param-value>true</param-value>
50        </init-param>
51    </filter>
52 
53    <!-- Make sure any request you want accessible to Shiro is filtered. /* catches all -->
54    <!-- requests.  Usually this filter mapping is defined first (before all others) to -->
55    <!-- ensure that Shiro works in subsequent filters in the filter chain:             -->
56    <filter-mapping>
57        <filter-name>shiroFilter</filter-name>
58        <url-pattern>/*</url-pattern>
59    </filter-mapping>
60  <filter>
61    <filter-name>encodingFilter</filter-name>
62    <filter-class
63            org.springframework.web.filter.CharacterEncodingFilter 
64        </filter-class>
65    <init-param>
66      <param-name>encoding</param-name>
67      <param-value>UTF-8</param-value>
68    </init-param>
69    <init-param>
70      <param-name>forceEncoding</param-name>
71      <param-value>false</param-value>
72    </init-param>
73  </filter>
74  <filter-mapping>
75    <filter-name>encodingFilter</filter-name>
76    <url-pattern>/*</url-pattern>
77  </filter-mapping>
78  
79  <servlet>
80    <servlet-name>springmvc</servlet-name>
81    <servlet-class
82            org.springframework.web.servlet.DispatcherServlet 
83        </servlet-class>
84    <init-param>
85      <param-name>contextConfigLocation</param-name>
86      <param-value>classpath:springmvc.xml</param-value>
87    </init-param>
88    <load-on-startup>1</load-on-startup>
89  </servlet>
90  <servlet-mapping>
91    <servlet-name>springmvc</servlet-name>
92    <url-pattern>*.action</url-pattern>
93  </servlet-mapping>
94  <welcome-file-list>
95    <welcome-file>index.jsp</welcome-file>
96  </welcome-file-list>
97</web-app>
所有回答列表(2)
sayHelloWorld的gravatar头像
sayHelloWorld  LV22 2015年11月24日

userService没有注入引起的

评论(0) 最佳答案
老司机不嘚劲的gravatar头像
老司机不嘚劲  LV7 2015年11月24日

没有启用springmvc的注解功能,类似下面这段配置:

<!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
 <context:component-scan base-package="com.xx">

    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友