import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 获取bean
*/
@Component
public class SpringBeanFactoryUtils implements ApplicationContextAware {
private static ApplicationContext context = null;
public static <T> T getBean(Class<T> type) {
return context.getBean(type);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringBeanFactoryUtils.context == null) {
SpringBeanFactoryUtils.context = applicationContext;
}
}
}
使用方法
@Autowired
RedisUtils redisUtils;
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
String token = getRequestToken((HttpServletRequest) request);
String url = ((HttpServletRequest) request).getServletPath();
//如果为登录,就放行
if ("/admin/user-info/login".equals(url)) {
return true;
}
try {
if(redisUtils == null){
redisUtils = SpringBeanFactoryUtils.getBean(RedisUtils.class);
}
...................................
本文介绍了如何在Spring框架中创建一个静态工具类`SpringBeanFactoryUtils`,该类实现了`ApplicationContextAware`接口,用于方便地获取Bean实例。在遇到需要使用Bean但不想直接依赖注入的情况下,可以调用`SpringBeanFactoryUtils.getBean()`方法。示例中展示了在权限校验方法中,如何通过该工具类动态获取`RedisUtils`实例进行业务处理。
2208

被折叠的 条评论
为什么被折叠?



