How to enable async supported for a spring MVC application in java configuration file (Not XML) - spring

I know how to enable async support in a XML configuration, I have done so for filters and servlets by adding tag
async-supported>true/async-supported
How to do it in a Java config file. I create a WebInit class which implements WebApplicationInitializer and overrides onStartUp -what should I do next?
public class WebInit implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
//What to do here, to move from XML to java config
}
}

Along the following lines -
ServletRegistration.Dynamic registration = container.addServlet(servletName, myServlet);
registration.setAsyncSupported(true);
EDIT:
Sorry, did not realize that you were looking for a Spring specific solution. With Spring MVC you would just extend a AbstractAnnotationConfigDispatcherServletInitializer assuming that your root and web contexts are #Configuration based. This initializer in-turn extends from AbstractDispatcherServletInitializer, this class has asyncSupported flag set by default.

Related

Why Servlet Filter can be Spring Bean?

What i know about Filter and Interceptor is that Filters as J2EE Specifications are part of the webserver and not the Spring framework. So some older articles explain that it is impossible to register filters as Spring Bean while Interceptor is possible.
But the results I got when I tested today is that Filters can be Spring Bean and also inject Spring Bean on Filters are possible too like Interceptors.
(I tested on SpringBoot Framework)
#Component
public class CustomFilterTest implements Filter {
#Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws ServletException, IOException {
chain.doFilter(request, response);
}
#Override
public void init(final FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
#Override
public void destroy() {
Filter.super.destroy();
}
}
#RestController
#RequiredArgsConstructor
public class ProductController {
private final CustomFilterTest customFilterTest;
#GetMapping("/test")
public ResponseEntity<Void> temp() {
System.out.println(customFilterTest);
return ResponseEntity.noContent().build();
}
}
Can anyone please explain to me?
We have to make a distinction between a regular Spring application and a Spring Boot application here. As with both, you can register a servlet filter as a bean, but the mechanism is a bit different.
Spring Framework
In plain Spring use the DelegatingFilterProxy to achieve this. The task of the DelegatingFilterProxy is to look for a bean with the same name as the filter in the root application context (the ApplicationContext registered through the ContextLoaderListener). This bean has to be your managed servlet filter.
#Configuration
#EnableWebMvc
public class WebConfiguration {
#Bean
public void YourFilter myFilter() { ... }
}
Then for the web application you would register a DelegatingFilterProxy with the name myFilter to make this work.
public class MyWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
public void onStartup(ServletContext servletContext)
throws ServletException {
super.onStartup(servletContext);
servletContext.addFilter("myFilter", DelegatingFilterProxy.class);
}
Spring Boot
In Spring Boot it is a bit different as Spring Boot is also in control of your servlet container, like Tomcat. It basically means that Tomcat is also a managed bean in your ApplicationContext and Spring Boot can inject dependencies into it. So when Spring Boot detects a bean for the servlet filter it will automatically add it to the filter chain (without the need of a DelegatingFilterProxy).
Which means only an #Bean for your filter is needed.
#Configuration
public class WebConfiguration {
#Bean
public YourFilter myFilter() { ... }
}
Additionally you can configure things like URLs etc. by adding an additional FilterRegistrationBean for this filter.
Conclusion
For plain Spring the DelegatingFilterProxy has been around since Spring 1.2 which was released in 2005. This means if you are reading really, really, really old articles (before 2005) this was true, however with the addition of the DelegatingFilterProxy, this isn't anymore. With the release of Spring Boot, this became even a lesser issue, is it more or less is the only way to register a filter (as a managed bean).

how can I change WebAppInitializer implements WebApplicationInitializer class to a main class

how can I change a WebAppInitializer implements WebApplicationInitializer class to a main class? the above mentioned class in spring mvc, now I want to convert it to spring boot. I created a spring boot project and created the packages and copied all of classes from spring mvc project to spring boot project I think I need to make some changes to WebAppInitializer class, but I do not know how to do that. the reason, when I try to run it eclipse does not allow me to run as it java/spring boot application. I am stock with this for a while. Thank you for your help.
public class WebAppInitializer implements WebApplicationInitializer {
private Logger log=LoggerFactory.getLogger(this.getClass());
private static final String DISPATCHER_SERVERLET_NAME="dispatcher";
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
log.info("starting up");
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(WebConfig.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
ServletRegistration.Dynamic registration = servletContext.addServlet(DISPATCHER_SERVERLET_NAME, dispatcherServlet);
registration.setLoadOnStartup(1);
registration.addMapping("/");
update:
the main class is on the top, all other packages are coming after that. these are my Annotation in my public class WebConfig implements WebMvcConfigurer { #EnableWebMvc, #Configuration, #ComponentScan(basePackages= "software.com"). Do I need to make any changes to WebConfig class?

onStartup method of WebApplicationInitializer never gets called

I have a Grails application. I am trying to set an active Spring profile by using the onStartup method of WebApplicationInitializer.
I have annotated this Java class with #Configuration but onStartup method never gets invoked.
package my.package;
#Configuration
public class MyWebApplicationInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.setInitParameter("spring.profiles.active", "test");
}
}
In Config.groovy I have added,
grails.spring.bean.packages = ['my.package']
I also tried adding following code in resources.groovy
xmlns context: "http://www.springframework.org/schema/context"
context."component-scan" "base-package": "my.package"
But whatever code changes I try onStartup method never gets called.
In my case I used application.yml and it worked in dev environment but after packaging it into a war using prod profile, for some reason it stopped picking up my java config annotated with #Configuration.
The solution was to modify Application.groovy as recommended in another question:
#ComponentScan("my.package")
class Application extends GrailsAutoConfiguration {
...
}
Note: Overriding packageNames() in Application.groovy recommended in the docs also doesn't work.

How to define #ComponentScan without XML and Annotation

How to Define ComponentScan Without Using annotation or Using XML in Spring? Is there any way to set componentScan using java code?
This blog says:
With the WebApplicationInitializer, Spring Framework Web MVC
applications can now rid themselves of web.xml. Additional
configuration/implementations are available for programmatically
registering the DispatcherServlet and configuring the Spring container
You should be using something like this:
public class Initializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.scan("com.package.name");
//the rest of initialization
}
}

spring boot with sitemesh

I'm using spring boot, and I would like to use sitemesh3 to my project.
I need to add the sitemesh filter, I create this class :
#Configuration
public class Initializer implements ServletContextInitializer{
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
//Sitemesh
FilterRegistration.Dynamic sitemesh = servletContext.addFilter("sitemesh", new ConfigurableSiteMeshFilter());
EnumSet<DispatcherType> sitemeshDispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
sitemesh.addMappingForUrlPatterns(sitemeshDispatcherTypes, true, "*.jsp");
}
}
I created the file sitemesh3.xml in WEB-INF directory but nothing happened, have I missed some configuration?
ServletContextInitializers aren't picked up with Spring Boot. Add the filter to your application configuration and wrap it in a FilterRegistrationBean.
See the Spring Boot reference guide.

Resources