0

I have a little experience with java Servlets and JSP, but i worked with Spring. In Spring we have interface named BeanPostProcessor. I used this interface implementation to create custom annotations. Code example

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;
    }

}

When i begin working with servlets i mentioned this annotation @WebServlet(urlPatterns = "/user/login") The question is: is it any functional in servlets that is similar with BeanPostProcessor in Spring and where is this annotation @WebServlet injected?

Example: I mean annotations in Spring are injected with BeanPostProcessor, for examle annotation @AutoWired is declared by AutoWiredAnnotationBeanPostProcessor class, but where the annotation @WebServlet is injected(or declared)

Almas Abdrazak
  • 3,209
  • 5
  • 36
  • 80
  • This annotation is used to declare a servlet and configure its mapping. As the javadoc (http://docs.oracle.com/javaee/7/api/javax/servlet/annotation/WebServlet.html) says. Annotations are not injected anywhere. Annotations are used by the developer to annotate the code. What exactly is your question? What are you trying to achieve? If you want to know how servlets work, why don't you read the freely available specifications? – JB Nizet Sep 04 '17 at 06:28
  • Sorry for unclear question, i add more details to question – Almas Abdrazak Sep 04 '17 at 07:23

1 Answers1

0

Servlets are not managed by Spring Container. So their annotations are processed by the servlet api implementation they run on, i.e. Tomcat.

Depending on what you want to achieve, you can simply extends HttpServlet and override the init method with your logic.

If you need to do some wiring you can also take advantage of SpringBeanAutowiringSupport. See also

Davide Cavestro
  • 473
  • 5
  • 13