Autwiring servletContext versus servletContextAware implementation

I saw two ways to get a servletContextbean in a service / controller.

1) simple way - just autowiring:

@Autowired
ServletContext servletContext;

2) another way is to implement the interface servletContextAware:

@RestController("/mycontroller")
public myController implements ServletContextAware {

    private ServletContext context;

    @Override
    public void setServletContext(ServletContext context) {
        this.context = context;
    }

   public String getContextPath(){
   return context.getContextPath();
  }

}

What are the pros and cons of these two? Which one is recommended?

+4
source share
1 answer

No one answered, so I will give it back.

The annotation version is simpler, but in cases where auto-installation is not enabled (or in versions of Spring before this function), then only the version will work ServletContextAware.

The recommended method is the first if you have enabled this functionality.

-one
source

All Articles