当时用springsecurity做动态加载权限时用到了鉴权(AccessDecisionVoter实现类),在这个类中没有办法获取ioc中的bean(不知道为啥),翻阅很多资料,找到一些解决办法和发现的一些问题记录下。
可以用到spring的ApplicationContext来获取ioc中的bean,ApplicationContext在spring初始化的时候会把所有的配置加载进去,相当于全局配置,所以可以在AccessDecisionVoter实现类中用ApplicationContext来拿到ioc容器中的bean,如下
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component("applicationContextHelper")
public class ApplicationContextHelper implements ApplicationContextAware {
@Autowired
private static ApplicationContext applicationContext;
// spring容器中配置bean之后,会在项目启动的时候给applicationContext赋值
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
public static <T> T popBean(Class<T> clazz) {
if (applicationContext == null) {
return null;
}
return applicationContext.getBean(clazz);
}
public static <T> T popBean(String name, Class<T> clazz) {
if (applicationContext == null) {
return null;
}
return applicationContext.getBean(name, clazz);
}
}
注意点:需要实现ApplicationContextAware 接口,不然获取不到ApplicationContext实例。