java工作随笔

手动注入bean

使用:
UserDchuMapper userDchuMapper = SpringContextUtil.getBean(UserDchuMapper.class);

包:
package org.hzero.oauth.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}

手动进行退出登录

TokenStore tokenStore = SpringContextUtil.getBean(TokenStore.class);
SessionRegistry sessionRegistry = SpringContextUtil.getBean(SessionRegistry.class);

//这部分功能类似于我在界面强制一个用户强制退出,一个token,一个session
//处理token
OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(accessToken);
tokenStore.removeAccessToken(oAuth2AccessToken);
//处理session
List<String> userSessions = new ArrayList<>();
List<Object> allPrincipals = sessionRegistry.getAllPrincipals();
for (Object principal : allPrincipals){
   User user =  (User) principal;
   List<SessionInformation> sessions = sessionRegistry.getAllSessions(user, false);
   for (SessionInformation sessionInformation:sessions){
      String sessionId = sessionInformation.getSessionId();
      userSessions.add(sessionId);
      }
}
if(!CollectionUtils.isEmpty(userSessions)){
   for(String sessionId:userSessions){
       sessionRegistry.removeSessionInformation(sessionId);
   }
}

你可能感兴趣的:(java,开发语言)