How to define #ComponentScan without XML and Annotation - spring

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

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?

Spring Boot - access component inside a servlet

I have a spring boot application that serves my jersey based api. I have a requirement to have the services layer serve blob data to a client as a stream. I wrote a servlet to do that and configured it as follows.
#Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(new BlobReaderServlet(),"/blobReader/*");
}
However, in the servlet code I can't seem to inject any components (they are all null). I need to inject a component that actually loads the blob data from the database.
#WebServlet(name = "BlobReaderServlet",
urlPatterns = {"/blobreader"})
#Component
public class BlobReaderServlet extends HttpServlet {
Logger logger = Logger.getLogger(this.getClass().getName());
#Inject
DocumentLoaderComponent blobLoader;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
I strongly suspect the servlet isn't a spring managed component after all and dependency injection isn't working. How can I get access to a component from the context?
UPDATE
It was much simpler than I thought.
#Override
public void init() throws ServletException {
ApplicationContext ac = (ApplicationContext) getServletConfig().getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
this.documentBlob = (DocumentBlob) ac.getBean("documentBlobBean");
}
You are correct that your servlet isn't a Spring managed bean. That is because you are instantiating the instance directly (i.e., calling new BlobReaderServlet() in your bean method). Another solution is to change your configuration class as follows:
#Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(blobReaderServlet(),"/blobReader/*");
}
#Bean
public BlobReaderServlet blobReaderServlet(){
return new BlobReaderServlet();
}
This will allow Spring to manage the instance and perform autowiring on it.

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

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.

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