Shiro独立应用程序

时间:2013-01-14 09:25:00

标签: java spring shiro

这是我的META-INF / spring / beans.xml

<bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager" />

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

<!-- Enable Shiro Annotations for Spring-configured beans.  Only run after -->
<!-- the lifecycleBeanProcessor has run: -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
    <property name="arguments" ref="securityManager"/>
</bean>

当我尝试测试时:

public static void main(String[] args) throws Exception {

    SecurityUtils.getSecurityManager()

}

我收到了这个错误:

org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton.  This is an invalid application configuration.

1 个答案:

答案 0 :(得分:3)

在引用其中定义的对象之前,必须首先创建Spring环境。这是在Spring Web应用程序中自动完成的,但是如果你有一个独立的应用程序(如上所示),你必须自己启动Spring。

试试这个:

import org.apache.shiro.mgt.SecurityManager;
...

public static void main(String[] args) throws Exception {

    String resource = "/META-INF/spring/beans.xml";

    ClassPathXmlApplicationContext appCtx = 
        new ClassPathXmlApplicationContext(resource);

    SecurityManager securityManager = 
        (SecurityManager)appCtx.getBean("securityManager");

    SecurityUtils.setSecurityManager(securityManager);

}