beanpostprocessor模拟

pbpqsu0x  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(203)

我对javaservlet和jsp有一点经验,但我使用spring。在spring中,我们有一个名为beanpostprocessor的接口。我使用这个接口实现来创建自定义注解。代码示例

public class InjectRandomIntAnnotationBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String string) throws BeansException {
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            InjectRandomInt annotation = field.getAnnotation(InjectRandomInt.class);
            if (annotation != null) {
                int min = annotation.min();
                int max = annotation.max();
                Random r = new Random();
                int i = min + r.nextInt(max - min);
                field.setAccessible(true);
                ReflectionUtils.setField(field, bean, i);
            }

        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String string) throws BeansException {
        return o;
    }

}

当我开始使用servlet时,我提到了这个注解 @WebServlet(urlPatterns = "/user/login") 问题是:servlets中是否有类似于spring中beanpostprocessor的函数,以及这个注解@webservlet是在哪里注入的?
示例:我的意思是spring中的注解是用beanpostprocessor注入的,例如,注解@autowired是由autowiredannotationbeanpostprocessor类声明的,但是注解@webservlet是注入(或声明)的

bqucvtff

bqucvtff1#

servlet不是由spring容器管理的。因此,它们的注解由它们运行的servlet api实现处理,即tomcat。
根据您想要实现的目标,您可以简单地扩展 HttpServlet 并覆盖 init method 用你的逻辑。
如果你需要做一些布线,你也可以利用 SpringBeanAutowiringSupport . 另请参见
未在web servlet中注入spring服务
我想使用spring在servlet中注入一个对象

相关问题