【问题标题】:BeanPostProcessor analog in servlet 3.0servlet 3.0 中的 BeanPostProcessor 模拟
【发布时间】:2017-09-04 06:13:52
【问题描述】:

我对 java Servlets 和 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") 问题是:servlet 中是否有任何与 Spring 中的 BeanPostProcessor 类似的功能?@WebServlet 这个注解是在哪里注入的?

示例: 我的意思是 Spring 中的注解是用 BeanPostProcessor 注入的,例如注解 @AutoWired 是由 AutoWiredAnnotationBeanPostProcessor 类声明的,但是注解 @WebServlet 是注入(或声明)的

【问题讨论】:

  • 这个注解用来声明一个servlet并配置它的映射。正如 javadoc (docs.oracle.com/javaee/7/api/javax/servlet/annotation/…) 所说。注释不会在任何地方注入。开发人员使用注释来注释代码。你的问题到底是什么?你想达到什么目的?如果您想了解 servlet 的工作原理,何不阅读免费提供的规范?
  • 抱歉问题不清楚,我在问题中添加了更多细节

标签: java servlets annotations


【解决方案1】:

Servlet 不由 Spring Container 管理。所以它们的注解由它们运行的​​ servlet api 实现处理,即 Tomcat。

根据您想要实现的目标,您可以简单地扩展 HttpServlet 并用您的逻辑覆盖 init method

如果你需要做一些接线,你也可以利用SpringBeanAutowiringSupport。另见

【讨论】:

    猜你喜欢
    • 2011-04-08
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    相关资源
    最近更新 更多