1
votes

Sorry for my english. How to get an authorized user in applicationContext.xml

Authentication class:

public class Authentication {
    public Account getAccount(){
        return (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}

And in file applicationContext.xml:

<bean id="Authentication" class="com.otv.util.Authentication">
</bean>

<bean id="CurrentAccount"
      factory-bean="Authentication"
      factory-method="getAccount"/>

But it is not working:

Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Principal' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public com.otv.model.entity.Account com.otv.util.Authentication.getAccount()] threw exception; nested exception is java.lang.NullPointerException]]

How can I get an authorized user in applicationContext.xml?

UPDATED

If I use as said holmis83. I get error:

org.hibernate.TransientObjectException:object references an unsaved transient instance - save the transient instance before flushing: com.otv.model.entity.Account

In 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 class:

@ManagedProperty(value="#{PostPaginatorDTO}")
public PostPaginatorDTO paginatorDTO;

public List<Post> getEntityList() {

    entityList=getDao().findByPostPaginatorDTO(getPaginatorDTO());

    return entityList;
}
1

1 Answers

0
votes

I guess you are trying to create a bean with another scope than default, which is singleton. Use scope attribute. If you want to use your scoped bean in a singleton bean, you better use a scoped proxy too.

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