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);
}
}
网友评论