Showing posts with label spring interview question. Show all posts
Showing posts with label spring interview question. Show all posts

Thursday, November 7, 2019

Difference Betwixt @Springbootapplication Vs @Enableautoconfiguration Annotations Inward Trammel Boot

Even though both @SpringBootApplication as well as @EnableAutoConfiguration tin hold out used to enable the auto-configuration characteristic of Spring Boot in that place is a subtle departure betwixt them. The @SpringBootApplication does much to a greater extent than than what @EnableAutoConfiguration do. It's genuinely a combination of 3 annotations: @Configuration which is used inward Java-based configuration on Spring framework, @ComponentScan to enable constituent scanning of components you lot write e.g. @Controller classes, as well as @EnableAutoConfgiuration itself, which is used to enable auto-configuration inward Spring Boot application. Spring Boot designers realize that these 3 annotations are oftentimes used together hence they bundled them into @SpringBootApplicaiton. Now, instead of 3 annotations you lot simply demand to specify 1 annotation on your Main class.

What is the departure betwixt @EnableAutoConfiguration as well as @SpringBootApplication is too a mutual Spring Boot interview interrogation as well as it was late asked 1 of my friends on his Java interview. Given the popularity of Spring Boot framework, it's skillful to know such questions earlier you lot become for your side past times side Java interview.

In this article, I'll explicate what does the @SpringBootApplication as well as @EnableAutoConfiguration practise as well as highlight about of import departure betwixt them hence that you lot tin respond this interrogation alongside confidence if you lot plow over to come across them inward your interview.




1. What is Auto-Configuration inward Spring Boot?

If you lot don't know, Spring Boot aims to simplify Java evolution alongside Spring framework. Currently, Spring does a lot for you lot but inward return, it too asks a lot from you lot inward damage of configuration as well as dependency management, Spring Boot aims to solve that problem.

The Spring Boto auto-configuration feature tries to automatically configure your Spring application based upon the JAR dependency you lot get got added inward the classpath.

For example, if HSQLDB is nowadays on your classpath as well as you lot get got non configured whatsoever database manually, Spring volition auto-configure an in-memory database for you.

By default, this auto-configuration characteristic is non enabled as well as you lot demand to opt-in for it past times adding the @EnableAutoConfiguration or @SpringBootApplicaiton annotations to 1 of your @Configuration classes, by as well as large the Main bird which is used to run your application.

Though, this is simply the tip of the iceberg. Spring Boot auto-configuration takes to a greater extent than than 200 such determination to configure your application, If you lot are interested inward learning to a greater extent than then Spring Framework Master Class - Beginner to Expert is a skillful course of report to larn Spring Boot inward depth.

 in that place is a subtle departure betwixt them Difference betwixt @SpringBootApplication vs @EnableAutoConfiguration annotations inward Spring Boot




2. Difference betwixt @EnableAutoConfiguration as well as @SpringBootApplication

Now that nosotros know what is @SpringBootApplication as well as @EnableAutoConfiguration annotation as well as what practise they do, it's fourth dimension to highlight about of import departure betwixt them.

Here is a duad of worth-noting departure betwixt @SpringBootApplication as well as @EnableAutoConfiguration annotations of Spring Boot:

1. Availability
The @SpringBootApplicaiton is relatively novel than @EnableAutoConfiguration. It was introduced inward Spring Boot 1.2 release piece @EnableAutoConfiguation is nowadays shape the Spring Boot 1.0 release.


2. Purpose
The clear piece of work of @EnableAutoConfiguration is to enable automatic configuration characteristic of Spring Boot application which automatically configures things if sure as shooting classes are nowadays inward Classpath e.g. it tin configure Thymeleaf TemplateResolver as well as ViewResolver if Thymeleaf is nowadays inward the classpath.

On the other hand, @SpringBootApplication does 3 things, it allows you lot to run the Main bird every bit a JAR alongside an embedded container. It enables Java configuration as well as it too enables Component Scanning.


3. Uses
It's not mandatory to position @SpringBootApplication to create a Spring Boot application, you lot tin even hence occupation @Configuration as well as @EnableAutoConfiguration individually every bit shown inward the illustration given inward side past times side point.


4. Control
The @EnableAutoConfiguration annotation allows you lot to selectively exclude sure as shooting classes from auto-configuration using exclude attribute every bit shown below:

@Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class MyConfiguration {   //.. Java code }

If the bird is non on the classpath, you lot tin occupation the excludeName attribute of the @EnableAutoConfiguration annotation as well as specify the fully qualified bird name.

If you lot desire to larn to a greater extent than well-nigh this annotation, I advise you lot reading Craig Walls' (author of Spring inward Action) about other masterpiece Spring Boot inward Action.

 in that place is a subtle departure betwixt them Difference betwixt @SpringBootApplication vs @EnableAutoConfiguration annotations inward Spring Boot



3. Important points

Now that you lot sympathise the departure betwixt @EnableAutoConfiguration as well as @SpringBootApplication, it's fourth dimension to revise about of import points well-nigh these 2 of import annotations.

1. You should annotate the Main bird or Bootstrap bird alongside the @SpringBootApplication, this volition permit you lot to run every bit a JAR alongside embedded spider web server Tomcat. If you lot desire you lot tin alter that to Jetty or Undertow.


2. The @SpringBootApplication is a combination of 3 annotations @Configuration (used for Java-based configuration), @ComponentScan (used for constituent scanning), as well as @EnableAutoConfiguration (used to enable auto-configuration inward Spring Boot).


3. The @EnableAutoConfiguration annotations enable auto-configuration features of Spring Boot which configures modules based on the presence of sure as shooting classes on the classpath. For example, if Thymeleaf JAR is nowadays inward classpath as well as Spring MVC is enabled e.g. using spring-boot-web-starter parcel as well as hence it tin automatically configure template resolver as well as persuasion resolver for you.


4. The @EnableAutoConfiguration annotation is based on @Conditional annotation of Spring 4.0 which enables conditional configuration.


5. In instance of auto-configuration, manually declared beans tin override beans automatically created past times auto-configuration feature. This is achieved past times using @ConditionalOnMissingBean of Spring 4.0


6. If you lot are using @EnableAutoConfiguration classes as well as hence you lot tin selectively exclude sure as shooting classes from auto-configuration past times using exclude every bit shown below:

@EnableAutoConfiguration(exclude=DataSourceAutoConfiguration.class)


7. The @SpringBootApplication annotation too provides aliases to customize the attributes of @EnableAutoConfiguration as well as @ComponentScan annotations.


That's all well-nigh the departure betwixt @SpringBootApplication as well as @EnableAutoConfiguration annotations of Spring Boot. As you lot learned, the @SpringBootApplication makes it tardily to enable auto-configuration as well as create a Bootstrap bird past times reducing the position out of annotations you lot usually demand i.e. instead of 3 annotations you lot simply demand one. But, if you lot demand to a greater extent than command over autoconfiguration as well as hence you lot should occupation @EnableAutoConfiguration, which allows you lot to exclude classes from auto-configuration.


Further Learning
Spring Framework Master Class - Beginner to Expert
Master Microservices alongside Spring Boot as well as Spring Cloud
Master Hibernate as well as JPA alongside Spring Boot inward 100 Steps
Spring Boot Reference Guide
REST alongside Spring MasterClass past times Eugen Parsaschiv
Spring Boot: Efficient Development, Configuration, as well as Deployment

Thanks for reading this article hence far. If you lot similar this article as well as my explains of departure betwixt @SpringBootApplication as well as @EnableAutoConfiguration as well as hence delight portion alongside your friends as well as colleagues. If you lot get got whatsoever questions or feedback as well as hence delight drib a note.

Friday, November 1, 2019

What Is The Purpose Of Dispatcherservlet Inward Jump Mvc? Interview Question

Hello guys, In today's article nosotros are going to utter over ane interesting as well as of import Spring MVC concepts, which is equally good a pop Spring Interview question. How DispatcherServlet industrial plant internally inward Spring MVC or What is the role of DispatcherServlet inward Spring MVC is around of the often asked Spring MVC Interview Questions. You powerfulness accept seen them already during your previous Java spider web evolution interviews exactly if you lot accept not, it's a practiced enquiry to know. In this article, I'll reply these questions past times explaining What is DispatcherServlet and its importance inward Spring MVC. The DispatcherServlet is ane of the of import components of the Spring MVC spider web framework as well as acts equally a Front Controller.

Similar to other Java spider web framework similar Struts 1.x as well as Struts 2.x, Spring MVC equally good uses a Front Controller (see Patterns of Enterprise Application Architecture)  to have all incoming asking as well as delegates to other components for farther processing similar Spring MVC controllers which are annotated using @Controller notation as well as ViewResolvers similar the InternalResourceViewResolver class.

Influenza A virus subtype H5N1 Front Controller is a mutual blueprint inward spider web application as well as used to have asking as well as delegate to other components inward the application for actual processing. The DispatcherServlet is a front end controller similar it provides a unmarried entry signal for a client asking to Spring MVC spider web application as well as forwards asking to Spring MVC controllers for processing.

How does DispatcherServlet know that which asking should last forwarded to which Controller? Well, Spring uses mapping handlers for that, which I volition explicate to you lot inward the adjacent department when we'll meet how DispatcherServlet industrial plant internally.

Apart from beingness a front end controller, DispatcherServlet equally good plays an of import role inward sentiment resolution, fault handling, locale resolution, topic resolution, etc. Btw, if you lot are non familiar amongst Spring inward full general as well as Spring MVC inward particular, you lot should equally good join Spring Framework 5: Beginner to Guru course on Udemy, ane of the most up-to-date courses on Spring framework as well as it equally good covers Spring 5.0.




How to configure DispatcherServlet inward Spring?

The DispatcherServlet is similar whatsoever other Servlet shape as well as it has to last declared within the deployment descriptor or web.xml file equally shown below:

<servlet>     <servlet-name>dispatcher</servlet-name>     <servlet-class>           org.springframework.web.servlet.DispatcherServlet     </servlet-class>     <init-param>         <param-name>contextConfigLocation</param-name>         <!--Defaults to WEB-INF\dispatcher-servlet.xml -->         <param-value>classpath:mvc-config.xml</param-value>     </init-param> </servlet> 

Its URL blueprint is normally "*" so that all incoming asking should acquire through Dispatcher servlet equally shown below:

<servlet-mapping>     <servlet-name>dispatcher</servlet-name>     <url-pattern>/*</url-pattern> </servlet-mapping>

I haven't shown hither but, DispatcherServlet is equally good normally preloaded using the load-on-startup tag of the deployment descriptor. You tin give null or positive value on this tag to pre-load a servlet, otherwise, the servlet volition alone last loaded when a asking volition arise.

If your servlet does a lot of chore on initialization similar DispatcherServlet which initializes all the beans declared inward its spider web context similar controllers, sentiment resolvers, as well as mapping handlers as well as so it could ho-hum downwardly the response time.


Btw, it's non the alone means to declare DispatcherServlet inward Spring MVC. From Spring 3.2 as well as Servlet 3.0 specification, you lot tin programmatically declare DispatcherServlet using ServletContainerInitializer interface.

This is a Servlet 3,0 characteristic which allows Servlet 3.0 compliant containers similar Tomcat vii or higher to scan as well as charge whatsoever shape which implements this interface.

Spring provides an implementation of this interface equally SpringServletContainerInitializer as well as a convenient shape called AbstractAnnotationConfigDispatcherServletInitialzer inward Spring 3.2 to configure DispatcherServlet without deployment descriptor.

This shape implements SpringServletContainerInitializer therefore automatically picked past times Servlet 3.0 compliant containers. See Spring MVC controllers. It uses @Controller as well as @RequestMapping notation for that purpose.

Once the asking is processed past times the Spring MVC controller, it returns a logical sentiment mention instead of the view. Though, you lot tin fifty-fifty configure Controler's handler methods to non homecoming whatsoever View mention past times declaring homecoming type equally void.

You tin fifty-fifty utilisation @ResponseBody notation inward the instance of REST to straight write the output to the HTTP response body. See REST amongst Spring course of report past times Eugen to acquire to a greater extent than near developing RESTful spider web services using Spring MVC.

When DispatherServlet receives sentiment name, it consults the ViewResolver to notice the right view. There is a chain of ViewResolver is maintained at the Spring MVC framework. They elbow grease to resolve the logical sentiment mention into a Physical resources similar a JSP page or a FreeMaker or Velocity template.

The ViewResolver are invoked inward order, if get-go inward the chain non able to resolve the sentiment as well as so it returns naught as well as adjacent ViewResolver inward the chain is consults.

Once the right sentiment is found, DispatcherServlet forwards the asking along amongst Model information to the View for rendering similar a JSP page.

By default, DispatcherServlet uses InternalResourceViewResolver which uses prefix as well as suffix to convert a logical sentiment mention e.g. "home" to /WEB-INF/home.jsp. The View interface equally good has getContentType() method, which returns content type the sentiment produces (JstlView has text/HTML). This is normally the default content type for requests handled past times the dispatcher servlet inward Spring. See Spring MVC for Beginners inward 25 Steps to acquire to a greater extent than near asking handing inward Spring MVC.

Here is a squeamish diagram which explains how DispatcherServlet industrial plant internally inward Spring MVC

s article nosotros are going to utter over ane interesting as well as of import Spring MVC concepts What is the utilisation of DispatcherServlet inward Spring MVC? Interview Question



In short, DispatcherServlet is used next things inward Spring MVC:
  1. Receives all asking equally Front Controller  and provides a unmarried entry signal to the application
  2. Mapping requests to right Spring MVC controller
  3. Consulting ViewResolvers to notice right View
  4. Forwarding asking to chosen View for rendering
  5. Returning the response to the client
  6. Creates web-context to initialize the web-specific beans like controllers, sentiment resolvers as well as handler mapping

That's all near what is the utilisation of DispatcherServlet inward Spring framework. It's is ane of the cardinal components of Spring MVC which is used to have all incoming asking as well as forrad them to right controllers for actual processing. It finds the right controllers past times using handler mappings like SimpleUrlHandlerMapping or BeanNameUrlHandlerMapping, which banking concern jibe if the edible bean mention is the same equally sentiment mention as well as the edible bean implements the View interface.

If you lot are using annotations as well as so it tin equally good utilisation @Controller and @RequestMapping annotations to notice the right controller to procedure a item request. Once the asking is processed past times the controller it returns a logical sentiment mention to DispatcherServlet.

The DispatcherServlet as well as so consults ViewResolver as well as LocalResolvers to notice the right View to homecoming the output. Once the right View is chosen, it forwards the asking to the View for rendering the response.

Further Reading
Spring Framework 5: Beginner to Guru
Spring Master Class - Beginner to Expert 
Spring MVC for Beginners inward 25 Steps

Other Spring related articles you lot may similar to explore this blog
  • How Spring MVC industrial plant internally? (answer)
  • Difference betwixt @RestController as well as @Controller? (answer)
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • 3 ways to acquire Spring Framework amend (article)
  • Free Courses to acquire Spring MVC as well as Spring Boot (courses)
  • How to enable Spring safety inward Java application? (answer)
  • Does Spring certification assistance inward Job as well as Career? (article)
  • How to prepare for Spring Certification? (guide)
  • 3 Best Practices Java Developers Can acquire from Spring (article)
  • Difference between @Autowired as well as @Injection annotations inward Spring? (answer)
  • 5 Spring as well as Hibernate online courses for Java developers (list)
  • 5 Spring Boot courses for Java developers (courses)
  • 5 courses to acquire Microservices amongst Spring Boot as well as Spring Cloud (courses)
Thanks for reading this article so far. If you lot similar this interview enquiry as well as so delight portion amongst your friends as well as colleagues. If you lot accept whatsoever enquiry or proposition as well as so delight drib a comment as well as I'll elbow grease to notice an reply for you. 

P.S. - If you lot desire to acquire how to railroad train RESTful Web Services using Spring Framework, banking concern jibe out Eugen Paraschiv's REST amongst Spring course. He has late launched the certification version of the course, which is amount of exercises as well as examples to farther cement the existent globe concepts you lot volition acquire from the course.

What Is Contextloaderlistener Inwards Trammel Mvc - 10 Things Coffee Programmer Should Know

The ContextLoaderListner is i of the of import components of the Spring MVC framework, in all likelihood the most of import later DispatcherServlet itself. It is used to exercise root context too responsible for loading beans which are shared past times multiple DispatcherServlet similar beans related to the service layer too information access layer. In general, When yous prepare Spring MVC based spider web application too too using Spring inwards the services layer, yous demand to render 2 application-contexts. The outset i is configured using ContextLoaderListener too the other is configured using DispatcherServlet. The DispatcherServlet is responsible for loading spider web ingredient specific beans similar controllers, view resolvers too handler mappings piece equally I said before, ContextLoaderListener is responsible for loading middle-tier too data-tier beans which forms the dorsum terminate of Spring applications.

The ContextLoaderListener is similar whatsoever other Servlet listener too it has to hold out declared inwards the deployment descriptor to hear to events. It listens for startup too shutdown of the server past times implementing ServletContextListener too accordingly creates too destroy Spring-managed beans.

Though, web.xml is only i agency to configure ContextLoaderListener inwards Spring MVC application. From Spring 3.1 too Servlet 3.0, yous tin too configure ContextLoaderListener without deployment descriptor too only using Java Configurations.

Spring 3.2 provides an abstract shape called AbstractAnnotationConfigDispatcherServletInitializer which receive got methods to render @Configuration classes for both root context too the spider web context specific to the DispatcherServlet.

The getRootConfigClasses() method of this shape render all @Configuration shape which should hold out move of root context too @getServletConfigClasses() method returns all @Configuration classes which should hold out specific to the DispatcherServlet. Though, if yous are non familiar alongside Java Configuration, Spring Framework 5: Beginner to Guru course on Udemy is a skillful resources to start with.

Though, i affair yous must recollect that this facility is exclusively available from Servlet 3.0 too yous demand a Servlet 3.0 electrical charge spider web server similar Tomcat seven or higher to programmatically exercise root context. If yous are running inwards Tomcat six or lower version too therefore yous receive got to occupation the web.xml to declare ContextLoaderListener.

One to a greater extent than affair to move on inwards heed is that ContextLoaderListener is optional. You tin withal exercise Spring MVC based spider web application without using this listener because all web-specific beans are loaded by DispatcherServlet itself.





10 points close ContextLoaderListener inwards Spring MVC

Here are closed to of the of import things close org.springframework.web.context.ContextLoaderListener shape a Java too Spring developer should know. It contains closed to of the key details equally good equally closed to lesser-known features of ContextLoaderListener, which is useful for both Spring 5.0 Developer Certification too Java Interviews which requires candidates from Spring background.

1) The ContextLoaderListener is similar whatsoever Servlet listener too implements both EventListener too ServletContextListener. Hence it listens for server startup too shutdown events.

2) Its project is to receive got the Spring configuration files equally input too creates the boundary managed beans equally per configuration too acquire inwards prepare during server startup too destroys them during server shutdown. Though it didn't exercise that itself, instead only delegate to ContextLoader equally good equally to ContextCleanupListener.

If yous are non familiar alongside Spring IOC container, It's amend to bring together a comprehensive Spring Framework course of written report like Spring Master Class - Beginner to Expert past times Ranga Karnan, a boyfriend blogger too experienced Java developer alongside Spring.

 is i of the of import components of the Spring MVC framework What is ContextLoaderListener inwards Spring MVC - 10 Things Java Programmer Should Know


3) You tin declare ContextLoaderListener inwards deployment descriptor or web.xml equally follows:

<web-app>   <listener>       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>   <context-param>     <param-name>contextConfigLocation</param-name>     <param-value>           /WEB-INF/config/applicationContext-service.xml          /WEB-INF/config/applicationContext-dao.xml      </param-value> </context-param> <servlet>         <servlet-name>dispatcher</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param>          <param-name>contextConfigLocation</param-name>          <param-value>             /WEB-INF/config/servlet-context.xml            ***/WEB-INF/config/applicationContext.xml***          </param-value> </init-param>     <load-on-startup>1</load-on-startup>  </servlet>   </web-app>

4) The actual initialization piece of work for the root application context is performed past times ContextLoader shape which is called past times ContextLoaderListener. This shape looks for a "contextClass" parameter at the web.xml context-param marking to discovery the type of the context shape too if no contextClass is defined than past times default it uses XmlWebApplicationContext.

It too processes a "contextConfigLocation" context-param too passes its value to the context instance. This parameter specifies the path for the boundary configuration file. It may incorporate multiple file paths which tin hold out separated past times whatsoever let out of commas too spaces, similar "WEB-INF/applicationContext1.xml, WEB-INF/applicationContext2.xml".

Even, Ant-style path patterns are supported equally well, similar "WEB-INF/*Context.xml,WEB-INF/spring*.xml" or "WEB-INF/**/*Context.xml". If non explicitly specified, the context implementation is supposed to occupation a default place (with XmlWebApplicationContext: "/WEB-INF/applicationContext.xml").


5) Along alongside loading the root application context, this shape tin optionally charge or obtain too claw upward a shared bring upward context to the root application context. You tin run into the loadParentContext(ServletContext) method for to a greater extent than information. You tin too read Spring inwards Action fifth Edition for to a greater extent than details, i of my favorite books to larn Spring too every Java developing using Spring should read it.

 is i of the of import components of the Spring MVC framework What is ContextLoaderListener inwards Spring MVC - 10 Things Java Programmer Should Know


6) When ContextLoaderListener is used along alongside DispatcherServlet, a root web-application-context is created outset equally said before too a child-context is too created past times dispatcher servlet which is attached to the root application-context. Refer documentation here.

7) In Servlet 3.0 compliant container, yous tin exercise root context without defining ContextLoaderListener inwards the deployment descriptor file. From Servlet 3.0 specification, announced inwards 2009, at that spot is a ServletContainerInitializer interface, whatsoever shape which implements this interface is automatically discovered past times Servlet 3.0 compliant servlet container similar Tomcat seven too higher.

8) Spring provides an implementation of ServletContainerInitializer interface equally SpringServletContainerInitializer too from Spring 3.2 yous tin too extend from AbstractAnnotationConfigDispatcherServletInitializer class. This tin exercise both root context too web-context specific to the DispatcherServlet.

The getServletCofnigClasses() method of this shape render all @Configuration classes which tin hold out loaded into spider web context too getRootConfigClasses() method returns all @Configuration classes which tin hold out move of root context.

9) In Spring MVC, the DispatcherServlet is expected to charge the edible bean configuration, spider web components such equally controllers, stance resolve too handler mappings piece ContextLoaderListener is expected to charge beans from service-tier too data-tier which forms the dorsum terminate of the application.

10) Another exercise goodness of the ContextLoaderListener is that it creates a WebApplicationContext too WebApplicationContext provides access to the ServletContext via ServletContextAware beans too the getServletContext() method. It too ties the lifecycle of the ApplicationContext to the lifecycle of the ServletContext equally explained inwards the classic Data Access object.

You tin configure ContextLoaderListener inwards the deployment descriptor too yous tin fifty-fifty render it the config place for the boundary configuration file. The ContextLoader listener listens for server startup too shutdown too accordingly exercise too destroyed Spring beans.

From Servlet 3.0 onwards, yous tin fifty-fifty configure ContextLoaderListener too root context without using deployment descriptor or web.xml file. The Servlet 3.0 specification provides an interface called ServletContainerInitializer too whatsoever shape which implements this interface volition automatically hold out scanned too loaded past times whatsoever Servlet 3.0 compliant container similar Tomcat seven or Tomcat 8.

From Spring 3.2 version Spring provides a convenient shape called AbstractAnnotationConfigDispatcherServlet whose getRootConfig() method tin hold out used to instantiate edible bean which lives inwards the root context.

The final affair yous should recollect close ContextLoaderListener is that it's optional inwards Spring MVC. You tin withal exercise Spring MVC based spider web application without declaring ConextLoaderListener too only declaring DispatcherServlet because all web-specific components similar controllers, stance resolvers too handler mappings are defined inwards the WebApplicationContext created past times Dispatcher servlet.

Further Learning
Spring Framework 5: Beginner to Guru
Spring Master Class - Beginner to Expert
courses)
  • Difference betwixt @Compoent, @Service, too @Controller inwards Spring? (answer)
  • 5 Free Spring Framework too Spring Boot Courses (courses)
  • Difference betwixt @Autowired too @Inject inwards Spring? (answer)
  • 15 Spring Boot Interview Questions alongside Answers (questions)
  • Difference betwixt @RequestParam too @PathVariable inwards Spring (answer)
  • 5 Spring Framework Books For Java Developers (books)
  • 20 REST alongside Spring Interview Questions for Web developers (questions)
  • 5 Spring Boot Features Java developer should larn (features)
  • 3 ways to larn Core Spring or Spring MVC amend (article)
  • 6 Resources to larn Spring Framework inwards Depth (resources)
  • Top 10 Spring Framework Interview Questions (questions)
  • 10 Spring MVC Annotations Every Java Dev should know (annotations)
  • Thanks for reading this article therefore far. If yous discovery these Spring MVC annotations useful too therefore delight part alongside your friends too colleagues on Facebook too Twitter. If yous receive got whatsoever questions or feedback too therefore delight drib a note.

    P. S. - If yous are novel to Spring Framework too looking for a hands-on course of written report then Learn Spring: The Certification Class past times Eugen Paraschive of Bealdug is in all likelihood the best course of written report to larn Spring v too Spring Boot 2 from scratch, inwards a guided, code-focused way.

    Thursday, October 31, 2019

    Top Five Saltation Kicking Annotations Amongst Examples For Coffee Developers

    Annotations bring completely changed the means y'all write Java code. It's straightaway impossible to write whatever Java code without using annotations but that's for good. They render a lot of value in addition to that's why it's of import for a Java developer to acquire familiar amongst essential annotations of the framework he or she is using. When I intend virtually Java, to a greater extent than or less of the essential annotations which come upward inwards our heed is @Override, @SuppressWarning in addition to @Deprecated. Similarly, if y'all are using Spring Boot framework, an extension of Spring framework which aims to simplify the Java evolution amongst Spring, y'all volition oftentimes cease of using a distich of annotations similar @SpringBootApplication or @EnableAutoConfiguration.

    Many Java developer simply blindly uses annotations without knowing that what they are in addition to what they do. They simply copy-paste the code without giving much thought.

    For example, the @SpringBootApplication annotation is required to most of the principal flat y'all write amongst Spring Boot, hence, most of the Java developer cease upward simply copy-pasting whole flat in addition to they trying to customize it for their ain need.

    Well, null is bad, equally long equally y'all know what y'all are doing but simply learning a chip of key never hurt. Even pocket-size information that what does the especially annotation do in addition to when to exercise them volition acquire out a long means inwards improving your agreement of the code y'all write or read.

    In club to span this gap, I am going to portion to a greater extent than or less of the essential Spring Boot annotations every Java developer should last familiar with. I'll simply render a quick overview amongst an instance for the sake to acquire out on this article brusk but y'all join Learn Spring Boot inwards 100 Steps to larn them inwards depth amongst to a greater extent than real-world examples.





    Spring Boot Annotations Java Developer should know

    Without wasting whatever to a greater extent than of your time, hither is my listing of to a greater extent than or less of the useful Spring Boot annotations which every Java developer using Spring Boot should last familiar with.

    1.@SpringBootApplication

    This is the most mutual Spring Boot annotations in addition to y'all volition honour it in all likelihood inwards every unmarried Spring Boot application. Since Spring Boot allows y'all to execute your Web application without deploying into whatever spider web server similar Tomcat.

    You tin laissez passer on the axe run them simply similar y'all tin laissez passer on the axe run the principal flat inwards Java, this annotation is used to annotate the principal flat of your Spring Boot application. It also enables the auto-configuration characteristic of Spring Boot.

    Here is an instance of using the @SpringBootApplication inwards Java:

    package boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;   @SpringBootApplication public class SpringBootDemo {  public static void main(String args[]) {   SpringApplication.run(SpringBootDemo.class, args); }  }  @RestController class HelloControler{   @RequestMapping("/") public String hello(){   return "Hello Spring Booot"; }  }

    This is the simplest instance of RESTful spider web service y'all tin laissez passer on the axe write using Spring in addition to Java. You tin laissez passer on the axe run this similar whatever Java application past times right-clicking on the source file in addition to "Run equally Java application" inwards Eclipse. After that, the embedded Tomcat server volition start in addition to deploy this RESTful spider web service.

    When y'all volition striking the URL http://localhost:8080/ (the default port for embedded tomcat server within Spring boot) y'all volition last greeted amongst "Hello Spring Boot".

    Now, coming dorsum to the @SpringBootApplication annotation, it's genuinely a combination of iii annotations - @Configuration, @ComponentScan, in addition to @EnableAutoConfiguration.

    If y'all know the @Configuration enables Java-based configuration in addition to the flat annotated amongst @Configuration tin laissez passer on the axe last used to define Spring Beans.

    The @ComponentScan enables element scanning so that controller or whatever other element flat y'all create volition last automatically discovered in addition to registered amongst Spring Bean.

    And, finally, the @EnableAutoConfiguration enables the auto-configuration characteristic of Spring Boot which tin laissez passer on the axe automatically configure surely Spring features based upon JAR available inwards Classpath. For example, if H2.jar is acquaint inwards the classpath, it tin laissez passer on the axe configure the H2 in-memory database within the Spring application context.

    As explained past times Dan Vega on his Spring Boot MasterClass, Spring Boot makes to a greater extent than than 200+ conclusion to gratis y'all from mutual configuration task. If y'all desire to customize those decisions y'all tin laissez passer on the axe do so.

     Annotations bring completely changed the means y'all write Java code Top v Spring Boot Annotations amongst Examples for Java Developers


    Btw, the @SpringBootApplication annotation is entirely available shape Spring Boot version 1.1, It wasn't purpose of Spring Boot's outset expose in addition to after added because they realize that almost all the applications were annotated amongst those iii annotations (@Configuration + @ComponentScan, in addition to @EnableAutoConfiguration).



    2.@EnableAutoConfiguration

    This is the master copy Spring Boot annotation which was added to enable the auto-configuration, the flagship Spring kicking characteristic which frees developers from mutual configuration task.

    The auto-configuration characteristic automatically configures things if surely classes are acquaint inwards the Classpath e.g. if thymeleaf.jar is acquaint inwards the Classpath so it tin laissez passer on the axe automatically configure Thymeleaf TemplateResolver in addition to ViewResolver.

    If y'all are non using @SpringBootApplication or running on Spring kicking version lower than 1.1 so y'all tin laissez passer on the axe exercise @EnableAutoConfiguration annotates to enable the auto-configuration characteristic of Spring Boot.


    Another affair which is worth knowing virtually @EnableAutoConfiguration is that it allows y'all to selectively ignore surely classes from auto-configuration using exclude attribute equally shown below:

    @Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class SpringBootDemo {   //.. Java code }

    If the flat is non on the classpath, y'all tin laissez passer on the axe exercise the excludeName attribute of the @EnableAutoConfiguration annotation in addition to specify the fully qualified flat name, equally explained past times Ranga Karnan on  Learn Spring Boot inwards 100 Steps course. One of the best course of report for beginners to larn Spring boot.

     Annotations bring completely changed the means y'all write Java code Top v Spring Boot Annotations amongst Examples for Java Developers


    Btw, this Spring Boot annotation is genuinely useful for experienced Spring Boot programmers who intend that Spring kicking is also opinionated in addition to desire to bring to a greater extent than or less command over the auto-configuration feature.



    3.@ContextConfiguration

    This annotation specifies how to charge the application context land writing a unit of measurement essay for the Spring environment. Here is an instance of using @ContextConfiguration along amongst @RunWith annotation of JUnit to essay a Service flat inwards Spring Boot.

    @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes=PaymentConfiguration.class) public class PaymentServiceTests{  @Autowired private PaymentService paymentService;  @Test public void testPaymentService(){    // code to essay PaymentService class  }  }

    In this example, @ContextConfiguration flat instructs to charge the Spring application context defined inwards the PaymentConfiguration class.

    Btw, fifty-fifty though it does a swell chore of loading Spring application context, it doesn't render total Spring kicking treatment.

    As explained past times Craig Walls inwards Spring Boot inwards Action, the Spring Boot applications are ultimately loaded past times SpringBootApplicaiton either explicitly or using the SpringBootServletInitializer.


     Annotations bring completely changed the means y'all write Java code Top v Spring Boot Annotations amongst Examples for Java Developers


    This non entirely leads beans inwards Spring application context but also enables logging in addition to loading of properties from external holding file like applicaiton.properties equally good equally other Spring Boot features. But, don't worry, at that spot is to a greater extent than or less other annotation which provides all of this in addition to y'all tin laissez passer on the axe exercise that to write a unit of measurement essay amongst Spring kicking treatment.



    4.@SpringApplicationConfiguration

    This is the annotation which addresses shortcomings of @ContextConfiguration annotation discussed inwards the previous section. It provides total Spring Boot handling to your essay classes e.g. it non entirely charge the beans inwards Spring application context but also enable logging in addition to loads properties from application.properties file.

    Btw, y'all should e'er exercise @SpringApplicaitonConfiguration instead of @ContextConfigruation for writing unit of measurement essay inwards Spring boot.

    Here is an instance of using @SpringApplicatoinConfiguration annotation inwards Spring boot:


    @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes=PaymentConfiguration.class) public class PaymentServiceTests{   ...  }

    This is the same instance nosotros bring seen inwards the in conclusion department but re-written using the @SpringApplicationConfiguration annotation this time. Again, I advise y'all cheque out the Spring Boot inwards Action mass to larn to a greater extent than virtually it, 1 of the best books to larn Spring Boot framework.





    5.@ConditionalOnBean

    Spring Boot defines several conditional annotations for auto-configuration like @ConditionalOnBean which tin laissez passer on the axe last used to apply a configuration if the specified edible bean has been configured.


    5.1 @ConditionalOnMissingBean
    Similarly, y'all bring @ConditionalOnMissingBean, which enables the configuration if the specified edible bean has non already been configured.

    @ConditionalOnClass
    The configuration is applied if the specified flat is available on the Classpath.


    5.2 @ConditioanlOnMissingClass
    This is the counterpart of the previous annotation. This configuration is applied if the specified flat is non acquaint on the Classpath.


    5.3 @ConditionalOnExpression
    The Configuration is applied if the given Spring Expression Language (SpEL) appear evaluates to true.


    5.4 @ConditionalOnJava
    The Configuration is applied if the version of Java matches a specific value or make of versions.

    Apart from these conditional annotations listed here, at that spot are to a greater extent than e.g. @ConditioalOnJndi, @ConditioanlOnProperty, @ConditioanlOnResource, @ConditionalOnWebApplication, in addition to @ConditionalOnNotWebApplication which plant depending upon the presence in addition to absence of to a greater extent than or less conditions.

    If y'all are interested to larn to a greater extent than virtually them, I advise to acquire out through Spring Framework 5: Beginner to Guru, 1 of the best course of report to larn Conditionals in addition to Spring Boot annotations.



    That's all virtually to a greater extent than or less of the essential Spring Boot annotations every Java developer should know. If y'all are using Spring Boot for creating Spring-based Java spider web application so y'all volition come upward across these annotations every straightaway in addition to then. Just knowing what they do in addition to where y'all tin laissez passer on the axe exercise volition laissez passer on y'all confidence land reading in addition to writing Spring kicking code.

    Further Learning
    Learn Spring Boot
    Master Java Web Services amongst Spring Boot
    Master Hibernate in addition to JPA amongst Spring Boot inwards 100 Steps


    Other Java in addition to Spring articles y'all may like
    • 5 Spring Boot Features Every Java Developer Should Know (features)
    • Top v Free Courses to larn Spring in addition to Spring Boot inwards 2019 (courses)
    • 5 Course to Master Spring Boot online inwards 2019 (courses)
    • 10 Things Java Developer should larn inwards 2019 (goals)
    • 10 Tools Java Developers exercise inwards their day-to-day life (tools)
    • 10 Tips to acquire a improve Java developer inwards 2019 (tips)
    • 3 Best Practices Java Programmers tin laissez passer on the axe larn from Spring (best practices)
    • 5 courses to larn Spring Boot in addition to Spring Cloud inwards 2019( courses)
    • 3 ways to modify Tomcat port inwards Spring Boot (tutorial)
    • 10 Spring MVC annotations Java developers should larn (annotations)
    • 15 Spring Boot Interview Questions for Java Programmers (questions)


    Thanks for reading this article so far. If y'all honour these Spring Boot annotations useful so delight portion amongst your friends in addition to colleagues. If y'all bring whatever questions or feedback so delight drib a note.

    How Dispatcherservlet Procedure A Asking Inward Saltation Mvc Application?

    One of the mutual inquiry inwards Spring MVC is, how does DispatcherServlet procedure a asking inwards Spring MVC? or What is the component division of DispatcherServlet inwards Spring MVC framework? This is an first-class inquiry to whatever Java or Spring spider web developer, the answer to this inquiry shows how much yous know nearly Spring MVC framework as well as its working. Actually, DispatcherServlet plays a pregnant component division inwards Spring MVC. It acts equally a front end controller, as well as all incoming asking passes through it, of course, yous tin configure this inwards URL designing of DispatcherServlet proclamation inwards web.xml, but this is the instance for many Spring based spider web application.

    The undertaking of DispatcherServlet is to notice the correct controller for processing the asking as well as thus when the handler method returns the logical thought name, it too consults thought resolvers to meet the actual view. Once the existent thought is found, as well as output is rendered, it sends the response dorsum to the client.

    The DispatchServlet is an implementation of the front end controller designing (see Patterns of Enterprise Application Architecture), but it does to a greater extent than than that. It non alone handles all asking but it is too responsible for thought resolution, locale resolution as well as topic resolution inwards Spring MVC framework, but the most of import undertaking of the DispatcherServlet is to finding the mapping handlers as well as routing the asking to them. I'll explicate that inwards the side yesteryear side paragraph.

    Btw, if yous convey worked inwards Spring MVC thus yous should already convey about basic ideas nearly things works, but if yous don't convey whatever prior sense as well as simply started amongst Spring framework as well as Spring MVC thus I propose yous to showtime acquire through a comprehensive course of didactics similar Spring Framework 5: Beginner to Guru course of didactics on Udemy.  One of the most useful courses on Spring framework




    How does DispatcherServlet procedure a asking inwards Spring MVC?

    As I said before, Dispatcher Servlet is used to grip all incoming requests as well as road them through dissimilar Spring Controllers for farther processing, but how does it notice which application needs to hold upwards routed to which controller or handlers?

    To compass this, DispatcherServlet uses HandlerMapping implementations. It tin grip whatever implementation of HandlerMapping interface, similar pre-built or customized implementations provided yesteryear the application to road incoming requests to handler objects.

    By default, it uses BeanNameUrlHandlerMapping as well as DefaultAnnotationHandlerMapping, which is driven using @RequestMapping annotation.

    In gild to notice the correct methods for treatment the request, it scans through all the classes declared using @Controller annotation as well as it too uses @RequestMapping annotation to notice the types as well as methods responsible for treatment requests.

    1. The @RequestMapping annotation tin map the asking yesteryear path, for illustration @RequestMapping("/home"),

    2. By HTTP method like
    @RequestMapping("/home", method=RequestMethod.GET)

    3. By asking parameters like
    @RequestMapping("/home", method=RequestMethod.POST, params="param1")

    4. And, yesteryear presence of http asking header like
    @RequestMapping("/home", header="content-type=text/*"). 


    You tin too apply @RequestMapping annotation at the course of didactics degree to filter incoming requests.

    Though, yous should recall that the @RequestMapping annotations volition alone hold upwards processed if a corresponding HandlerMapping (for type-level annotations) and/or HandlerAdapter (for method-level annotations) is introduce inwards the dispatcher servlet configuration file.

    This is the instance yesteryear default. However, if yous are defining custom HandlerMappings or HandlerAdapters, thus yous demand to brand certain that a corresponding custom DefaultAnnotationHandlerMapping and/or AnnotationMethodHandlerAdapter is defined equally good - provided that yous intend to exercise @RequestMapping.

    After processing the request, the Controller returns the logical thought elevate as well as model to DispatcherServlet. It thus consults to thought resolvers to notice the actual View to homecoming the output. The thought resolution strategy tin hold upwards specified using a ViewResolver implementation, yesteryear default, DispatcherServlet uses InternalResourceViewResolver to convert logical thought elevate to the actual View object similar a JSP.

    After this DispatcherServlet contacts the chosen view, similar a JSP file amongst model information as well as it renders the output depending on the model data. This rendered output is returned to the customer equally a response.

    Sometimes yous don't fifty-fifty demand a thought similar inwards the instance of RESTful Web services. Their handler method lead writes into response using @ResponseBody annotation as well as DispatcherServlet homecoming the answer to the client. See REST amongst Spring Certification class to acquire to a greater extent than nearly developing as well as testing RESTful Web service using Spring MVC.

    Also, inwards the Spring MVC framework, a spider web application tin define whatever publish of DispatcherServlet. Each servlet volition operate inwards its ain namespace, loading its ain application context amongst mappings, handlers, etc. Only the root application context equally loaded yesteryear ContextLoaderListener, if any, volition hold upwards shared.

    DispathcherServlet inwards Spring MVC

    Influenza A virus subtype H5N1 flick is worth a one thousand words, fifty-fifty a clumsy i similar this which nicely summarise what happens when a asking hitting to boundary container as well as how DispatcherServlet procedure a asking inwards Spring MVC application:

     One of the mutual inquiry inwards Spring MVC is How DispatcherServlet procedure a asking inwards Spring MVC Application?


    That's all nearly how DispatcherServlet procedure a spider web asking inwards Spring MVC. As I said, it scans through all @Controler classes as well as @RequestMapping to notice out all the handler methods as well as exercise a mapping of it. It thus routes an incoming asking to appropriate handlers, as well as when they homecoming a logical thought name, it uses ViewResolver implementations to resolve the elevate into a View object, which could hold upwards backed amongst whatever JSP or FreeMarker page.

    The thought thus renders the response which is sent to the customer yesteryear DispatcherServlet. In the instance of RESTful Web Services as well as @RestController classes or handler methods annotated amongst @ResponseBody, the response is lead sent to the customer equally no thought resolution happens.

    Further Reading
    How Spring MVC works?
    Spring MVC Interview Questions

    Thanks for reading this article thus far. If yous similar this Spring MVC tutorial, thus delight portion amongst your friends as well as colleagues. If yous convey whatever questions or feedback, thus delight driblet a note.