本文主要是介绍BeanPostProcessor使用之XssBeanPostProcessor,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
BeanPostProcessor
BeanPostProcessor是Spring框架中的一个重要的扩展点,它允许开发者在Bean初始化前后对Bean进行自定义处理。Spring中有很多内置的BeanPostProcessor,如AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、InitDestroyAnnotationBeanPostProcessor等。
开发者也可以自定义BeanPostProcessor,只需要实现BeanPostProcessor接口即可。BeanPostProcessor接口有两个方法:
- postProcessBeforeInitialization(Object bean, String beanName):在Bean初始化之前执行
- postProcessAfterInitialization(Object bean, String beanName):在Bean初始化之后执行
自定义BeanPostProcessor
自定义BeanPostProcessor也可以用来做许多有用的事情,如:
- 根据Annotation自动为Bean注入依赖
- 在Bean初始化后执行某些操作
- 利用代理机制为Bean添加一些行为
下面是一个简单的自定义BeanPostProcessor例子。
XssFilter是一个安全过滤组件,对提交的内容进行过滤,作为jar包引入。
但是为了动态的增加不过滤的url,选择从配置中读取配置,动态修改fliter的urlExclude。
@Component
public class XssBeanPostProcessor implements BeanPostProcessor, EnvironmentAware {private Environment environment;private static String FIELD_FILTER = "filter";private static String FIELD_URLEXCLUSION = "urlExclude";private static String CONFIG_PROPERTY = "fliterUrl";private static String beanNameOfFilterBean = "org.springframework.boot.web.servlet.FilterRegistrationBean";@Overridepublic Object postProcessBeforeInitialization(Object o, String s) throws BeansException {return o;}@SneakyThrows@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {if (bean instanceof FilterRegistrationBean) {try {String name = bean.getClass().getName();Class beanNameClz = Class.forName(name);changeField(beanNameClz, FIELD_FILTER, bean);} catch (Exception e) {e.printStackTrace();}}return bean;}private void changeField(Class clazz, String fieldName, Object obj) throws Exception {Object value = getField(clazz, fieldName, obj);// 获取到XssFilter过滤器if (Objects.nonNull(value) && value instanceof XssFilter) {XssFilter xssFilter = (XssFilter) value;// XssFilter的属性urlExclude为不过滤的urlObject urlExclusionValue = getField(xssFilter.getClass(), FIELD_URLEXCLUSION, xssFilter);// 获取配置中不过滤的urlString property = environment.getProperty(CONFIG_PROPERTY );if (Objects.nonNull(urlExclusionValue) && urlExclusionValue instanceof List && !StringUtils.isEmpty(property)) {List list = (List) urlExclusionValue;String[] split = property.split(",");List<String> objects = Lists.newArrayList(Arrays.asList(split));objects.addAll(list);Field field = ReflectionUtils.findField(xssFilter.getClass(), FIELD_URLEXCLUSION);// 反射修改ReflectionUtils.setField(field, value, objects);}}}private Object getField(Class clazz, String fieldName, Object obj) throws Exception {Field field = ReflectionUtils.findField(clazz, fieldName);if (Objects.nonNull(field)) {ReflectionUtils.makeAccessible(field);Object value = field.get(obj);return value;}return null;}@Overridepublic void setEnvironment(Environment environment) {this.environment = environment;}
}
这篇关于BeanPostProcessor使用之XssBeanPostProcessor的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!