Apache Shiro ThreadContext#bind(Subject) 与 ThreadContext.bind(SecurityManager)

Apache Shiro ThreadContext#bind(Subject) vs ThreadContext.bind(SecurityManager)

我刚刚在学习 Apache Shiro,遇到了一个问题。在我在网上看到的例子中,线程安全的入口点是下面的代码:

  try {
        ThreadContext.bind(subject);
        //main code here
    } finally {
        ThreadContext.unbindSubject();
    }

但是根据documentation有以下方法:

static void bind(SecurityManager securityManager) Convenience method that simplifies binding the application's SecurityManager instance to the ThreadContext.

static void bind(Subject subject) Convenience method that simplifies binding a Subject to the ThreadContext.

static SecurityManager unbindSecurityManager() Convenience method that simplifies removal of the application's SecurityManager instance from the thread.

static Subject unbindSubject() Convenience method that simplifies removal of a thread-local Subject from the thread.

谁能解释一下,我们何时(在什么情况下)需要绑定 Subject 以及何时需要绑定 SecurityManager?

这取决于你的代码在做什么,大多数时候你只需要引用你的主题,但是,如果你的自定义代码用 SecurityManager 做一些事情,Shiro 也提供了一个实用程序。

也就是说,在大多数情况下,您可能希望使用 subject.excute(...)https://shiro.apache.org/subject.html#thread-association

TL;DR,除非您有直接使用安全管理器的代码,否则请通过 subject.execute

自动使用线程关联