Java 我可以使用SpringDI将会话属性注入到webapplication的POJO中吗

Java 我可以使用SpringDI将会话属性注入到webapplication的POJO中吗,java,spring,struts2,Java,Spring,Struts2,我使用的是Struts2框架,在POJO类中有以下方法 public String execute() { setUserPrincipal(); //do something someMethod(getUserPrincipal().getLoggedInUserId()); return SUCCESS; } setUserPrincipal()方法如下所示 public void setUserPrincipal() { this.princip

我使用的是Struts2框架,在POJO类中有以下方法

public String execute() {
    setUserPrincipal();
    //do something
    someMethod(getUserPrincipal().getLoggedInUserId());
    return SUCCESS;
}
setUserPrincipal()
方法如下所示

public void setUserPrincipal() {
    this.principal = (UserPrincipal) getServletRequest().getSession().getAttribute("principal");
}
基本上,它只是简单地获取一个名为“principal”的会话属性并进行设置,这样我就可以找出登录用户是谁。调用
setUserPrincipal()
执行此操作在我的大多数POJO中都很常见,而且在测试该方法时也会遇到麻烦,因为我必须设置会话属性


有没有一种方法可以使用Spring或其他工具自动将会话属性注入POJO?

不知道如何注入会话,但可能有一段AOP代码,可以在执行之前设置主体

以下是一些文档:


我只使用了一点Struts2,但它们有一个拦截器堆栈,您可以将其绑定到特定操作。您可以创建自己的拦截器来注入会话变量

public interface UserAware 
{
   void setUserPrincipal(String principal);
}

// Make your actions implement UserAware

public class MyInterceptor implements Interceptor
{
   public String intercept(ActionInvocation inv) throws Exception
   {
      UserAware action = (UserAware) inv.getAction();
      String principal = inv.getInvocationContext().getSession().get("principal");
      action.setUserPrincipal(principal);

      return inv.invoke();
   }
}

正如我所说,Struts2没有多少经验,因此这是未经测试的,但我认为想法是存在的。

有一个Spring-Struts2集成模块,可以提供帮助。顺便说一句,您可以使用Spring安全性,然后在代码中的任何地方访问主体。