由于作业异步操作,它们无法访问用户的会话。需要找到一个解决方案,以便作业可以访问用户的会话(如果用户当时仍处于登录状态)。
用户会话
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class UserPrincipal implements UserDetails {
private User user;
private Collection<SimpleGrantedAuthority> grantedAuthorities;
public UserPrincipal(User user) {
Assert.notNull(user);
this.user = user;
Set<SimpleGrantedAuthority> authorities = new LinkedHashSet<>();
for (Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getName().toUpperCase(Locale.ENGLISH)));
}
grantedAuthorities = Collections.unmodifiableCollection(authorities);
}
}
抽象作业类
public abstract class Job implements Runnable {
protected Logger logger = LoggerFactory.getLogger(getClass());
protected Job() {
}
@Override
public final void run() {
logger.debug("starting work");
/* code goes here */
logger.debug("work is done");
}
}
职位类别
@Component
@Scope(value = "prototype")
public class ProcessLoggingJob extends Job {
@Override
protected void work(Map<String, Object> context) throws Exception {
// need to access user session here
}