美文网首页
动态获取上下文和Bean

动态获取上下文和Bean

作者: 鼓上骚 | 来源:发表于2019-08-27 10:27 被阅读0次

    SpringContextUtil

    package cn.czyfwpla.sys.config;
    
    import org.springframework.context.ApplicationContext;
    
    /**
     * @description: 获取上下文环境
     * @author wonder
     * @date 2019/08/20 14:13
     */
    public class SpringContextUtil {
        private static ApplicationContext applicationContext;
    
        //获取上下文
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    
        //设置上下文
        public static void setApplicationContext(ApplicationContext applicationContext) {
            SpringContextUtil.applicationContext = applicationContext;
        }
    
        //通过名字获取上下文中的bean
        public static Object getBean(String name){
            return applicationContext.getBean(name);
        }
    
        //通过类型获取上下文中的bean
        public static Object getBean(Class<?> requiredType){
            return applicationContext.getBean(requiredType);
        }
    }
    
    

    在application中设置上下文

    @SpringBootApplication
    public class Application {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext application = SpringApplication.run(Application.class, args);
            SpringContextUtil.setApplicationContext(application);
        }
    }
    

    通过springContextUtil获取上下文环境或Bean

    public class QQAuthenticationManager implements AuthenticationManager {
    
        private LoadUser loadUser;
    
        private UserService userService;
    
        private List<SimpleGrantedAuthority> authorities = new ArrayList<>();
    
        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            userService = (UserService)SpringContextUtil.getBean(UserService.class);
            loadUser = (LoadUser)SpringContextUtil.getBean(LoadUser.class);
            ServletRequestAttributes attr = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
            HttpSession session= attr.getRequest().getSession(true);
            String accessToken = authentication.getName();
            String openId = (String) authentication.getCredentials();
            session.setAttribute("qqOpenId",openId);
            SysUser sysUser = new SysUser();
            if (accessToken != null && openId != null) {
                sysUser = userService.getUserByQQOpenid(openId);
                if (sysUser == null){
                    throw new UsernameNotFoundException("该用户未注册");
                }
            }
            return new UsernamePasswordAuthenticationToken(loadUser.loadUserByUsername(sysUser.getAccount()),null, authorities);
        }
    
    }
    
    
    

    相关文章

      网友评论

          本文标题:动态获取上下文和Bean

          本文链接:https://www.haomeiwen.com/subject/cgdsectx.html