【问题标题】:Spring Security: how to get an authorized user in applicationContext.xmlSpring Security:如何在 applicationContext.xml 中获取授权用户
【发布时间】:2015-02-11 00:17:10
【问题描述】:

对不起我的英语。如何在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:object 引用了一个未保存的瞬态 instance - 在刷新之前保存瞬态实例: 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;
}

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    我猜你正在尝试创建一个具有不同于默认范围的 bean,即单例。使用scope 属性。如果你想在单例 bean 中使用作用域 bean,最好也使用作用域代理。

    <bean id="CurrentAccount" factory-bean="Authentication" factory-method="getAccount" scope="request">
      <aop:scoped-proxy/>
    </bean>
    

    【讨论】:

    • @sergeyivanov 错误看起来有点不相关。搜索“TransientObjectException”或提出新问题?
    猜你喜欢
    • 2015-08-05
    • 2015-10-21
    • 1970-01-01
    • 2020-07-28
    • 2014-11-09
    • 1970-01-01
    • 2012-11-21
    • 2016-09-29
    • 1970-01-01
    相关资源
    最近更新 更多