![](/img/trans.png)
[英]how to access applicationContext.xml in Spring controller?
[英]Spring Security: how to get an authorized user in applicationContext.xml
对不起我的英语不好。 如何在applicationContext.xml中获得授权用户
Authentication
类别:
public class Authentication {
public Account getAccount(){
return (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
并在文件applicationContext.xml中:
<bean id="Authentication" class="com.otv.util.Authentication">
</bean>
<bean id="CurrentAccount"
factory-bean="Authentication"
factory-method="getAccount"/>
但它不起作用:
加载应用程序时发生异常:java.lang.IllegalStateException:ContainerBase.addChild:开始:org.apache.catalina.LifecycleException:org.springframework.beans.factory.BeanCreationException:创建在ServletContext资源中定义名称为“ Principal”的bean时出错WEB-INF / applicationContext.xml]:实例化Bean失败; 嵌套的异常是org.springframework.beans.factory.BeanDefinitionStoreException:工厂方法[public com.otv.model.entity.Account com.otv.util.Authentication.getAccount()]引发了异常; 嵌套的异常是java.lang.NullPointerException]]
如何在applicationContext.xml中获得授权用户?
如果我用holmis83说的话。 我得到错误:
org.hibernate.TransientObjectException:对象引用了一个未保存的瞬态实例-在刷新之前保存该瞬态实例:com.otv.model.entity.Account
在applicationContext.xml中:
<bean id="Authentication" class="com.otv.util.Authentication"/>
<bean id="CurrentAccount" factory-bean="Authentication" factory-method="getAccount" scope="request">
<aop:scoped-proxy/>
</bean>
<bean id="PostPaginatorDTO" class="com.otv.model.dto.paginator.PostPaginatorDTO" scope="request">
<property name="account" ref="CurrentAccount" />
</bean>
PostBean
类:
@ManagedProperty(value="#{PostPaginatorDTO}")
public PostPaginatorDTO paginatorDTO;
public List<Post> getEntityList() {
entityList=getDao().findByPostPaginatorDTO(getPaginatorDTO());
return entityList;
}
启动期间,安全上下文中没有授权用户。 因此,您将面临NullPointerException
。
除去CurrentAccount
Bean,并将Authentication
Bean重命名为:
<bean id="CurrentAccount" class="com.otv.util.Authentication">
</bean>
现在,您可以将CurrentAccount
Bean连接到服务中,并在运行时检索授权用户:
currentAccount.getAccount()
我强烈建议将com.otv.util.Authentication
重命名为com.otv.util.CurrentAccount
,以免与org.springframework.security.core.Authentication
com.otv.util.CurrentAccount
。
我猜您正在尝试使用默认范围之外的另一个范围(即单例)创建一个bean。 使用scope
属性。 如果要在单例bean中使用作用域bean,最好也使用作用域代理。
<bean id="CurrentAccount" factory-bean="Authentication" factory-method="getAccount" scope="request">
<aop:scoped-proxy/>
</bean>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.