我刚刚学习Apache Shiro,面临一个问题。在互联网上看到的例子中,线程安全的切入点是下面的代码。
try {
ThreadContext.bind(subject);
//main code here
} finally {
ThreadContext.unbindSubject();
}
然而,根据 文件 有以下方法。
static void bind(SecurityManager securityManager) 简化将应用程序的SecurityManager实例绑定到线程上下文的方便方法。
static void bind(Subject subject) 简化将Subject绑定到ThreadContext的便捷方法。
static SecurityManager unbindSecurityManager() 简化从线程中移除应用程序的SecurityManager实例的便捷方法。
static Subject unbindSubject() 简化从线程中移除线程本地Subject的便利方法。
谁能解释一下,什么时候(在什么情况下)我们需要绑定Subject,什么时候需要绑定SecurityManager?
这取决于你的代码在做什么,大多数时候,你只需要对你的Subject的引用,但是,如果你的自定义代码用SecurityManager做一些事情,Shiro也提供了一个实用程序。
也就是说,您可能想要使用 subject.excute(...)
而不是大多数情况下。https:/shiro.apache.orgsubject.html#thread-association。
TL;DR,除非你有直接使用安全管理器的代码,否则就会通过 subject.execute