HTML Tutorial

Core Java Interview Questions and Answers Hibernate Interview Questions and Answers JSF Interview Questions And Answers JSF Interview Questions And Answers JSP Interview Questions and Answers 50 Servlet Interview Questions and Answers Struts2 Interview Questions and Answers

JAVA 10 Tutorial


Spring Interview Questions and Answers

Spring Framework is a standout amongst the most prominent Java EE structure for web applications. Dependency Injection and Aspect Oriented Programming are at the core of Spring structure. On the off chance that you are great in Spring Framework, odds of getting chose gets high.

You should bookmark this post since Spring Framework is much greater and chances are that I will continue adding more inquiries to this rundown and you would prefer not to miss them out.

Spring Interview Questions and Answers

  1. What is Spring Framework?

    Spring is a standout amongst the most broadly utilized Java EE system. Spring structure center ideas are "Reliance Injection" and "Perspective Oriented Programming".

    Spring system can be utilized in typical java applications likewise to accomplish free coupling between various parts by actualizing reliance infusion and we can perform cross cutting assignments, for example, logging and validation utilizing spring support for viewpoint arranged programming.

    like spring since it gives a ton of highlights and distinctive modules for explicit errands, for example, Spring MVC and Spring JDBC. Since it's an open source system with a great deal of online assets and dynamic network individuals, working with Spring structure is simple and fun at same time.

  2. What are a portion of the critical highlights and focal points of Spring Framework?

    Spring Framework is based over two plan ideas – Dependency Injection and Aspect Oriented Programming.

    Some of the highlights of spring system are:

    • Lightweight and next to no overhead of utilizing structure for our development.
    • Dependency Injection or Inversion of Control to compose segments that are autonomous of one another, spring holder deals with wiring them together to accomplish our work.
    • Spring IoC holder oversees Spring Bean life cycle and task explicit setups, for example, JNDI lookup.
    • Spring MVC structure can be utilized to make web applications just as relaxing web administrations fit for returning XML just as JSON response.
    • Support for exchange the board, JDBC activities, File transferring, Exception Handling and so forth with almost no designs, either by utilizing comments or by spring bean setup file.

    Some of the benefits of utilizing Spring Framework are:

    • Reducing direct conditions between various parts of the application, generally Spring IoC holder is in charge of introducing assets or beans and infuse them as dependencies.
    • Writing unit experiments are simple in Spring system in light of the fact that our business rationale doesn't have direct conditions with real asset execution classes. We can without much of a stretch compose a test setup and infuse our counterfeit beans for testing purposes.
    • Reduces the measure of standard code, for example, introducing objects, open/close assets. I like JdbcTemplate class a great deal since it encourages us in evacuating all the standard code that accompanies JDBC programming.
    • Spring system is isolated into a few modules, it encourages us in keeping our application lightweight. For instance, in the event that we needn't bother with Spring exchange the board highlights, we don't have to include that reliance in our project.
    • Spring system bolster a large portion of the Java EE includes and even considerably more. It's dependably over the new innovations, for instance there is a Spring venture for Android to enable us to compose better code for local android applications. This makes spring structure a total bundle and we don't have to take care of various system for various requirements.
  3. What do you comprehend by Dependency Injection?

    Dependency Injection structure patternallows us to evacuate the hard-coded conditions and make our application inexactly coupled, extendable and viable. We can actualize reliance infusion example to move the reliance goals from arrange time to runtime.

    Some of the advantages of utilizing Dependency Injection are: Separation of Concerns, Boilerplate Code decrease, Configurable parts and simple unit testing.

    How do we actualize DI in Spring Framework?

    We can utilize Spring XML based just as Annotation based arrangement to actualize DI in spring applications. For better understanding, Spring Dependency Injectionexample where you can learn both the ways with JUnit experiment. The post additionally contains test venture compress document, that you can download and play around to learn more.

    What are the advantages of utilizing Spring Tool Suite?

    We can introduce modules into Eclipse to get every one of the highlights of Spring Tool Suite. Anyway STS accompanies Eclipse with some other essential stuffs, for example, Maven support, Templates for making diverse kinds of Spring undertakings and tc server for better execution with Spring applications.

    I like STS in light of the fact that it features the Spring parts and in the event that you are utilizing AOP pointcuts and advices, at that point it unmistakably demonstrates which techniques will go under the particular pointcut. So as opposed to introducing everything all alone, I lean toward utilizing STS when creating Spring based applications.

  4. Name a portion of the critical Spring Modules?

    Some of the critical Spring Framework modules are:

    • Spring Context – for reliance injection.
    • Spring AOP – for angle arranged programming.
    • Spring DAO – for database activities utilizing DAO pattern
    • Spring JDBC – for JDBC and DataSource support.
    • Spring ORM – for ORM apparatuses bolster, for example, Hibernate
    • Spring Web Module – for making web applications.
    • Spring MVC – Model-View-Controller execution for making web applications, web administrations etc.
  5. What do you comprehend by Aspect Oriented Programming?

    Enterprise applications have some basic cross-cutting worries that is material for various kinds of Objects and application modules, for example, logging, exchange the board, information approval, validation and so forth. In Object Oriented Programming, seclusion of utilization is accomplished by Classes while in AOP application measured quality is accomplished by Aspects and they are designed to play hooky methods.

    What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?

    Aspect: Aspect is a class that executes cross-cutting concerns, for example, exchange the executives. Perspectives can be an ordinary class arranged and after that designed in Spring Bean setup document or we can utilize Spring AspectJ backing to announce a class as Aspect utilizing @Aspect annotation.

    Pointcut: Pointcut are customary articulations that is coordinated with join focuses to decide if counsel should be executed or not. Pointcut utilizes various types of articulations that are coordinated with the join focuses. Spring system utilizes the AspectJ pointcut articulation language for deciding the join focuses where guidance strategies will be applied.

    Join Point: A join point is the particular point in the application, for example, technique execution, special case taking care of, changing article variable qualities and so forth. In Spring AOP a join focuses is dependably the execution of a method.

    Advice Arguments: We can pass contentions in the counsel techniques. We can utilize args() articulation in the pointcut to be connected to any technique that coordinates the contention design. In the event that we utilize this, at that point we have to utilize a similar name in the guidance strategy from where contention type is resolved.

    What is the distinction between Spring AOP and AspectJ AOP?

    AspectJ is the business standard usage for Aspect Oriented Programming while Spring actualizes AOP for a few cases. Principle contrasts between Spring AOP and AspectJ are:

    • Spring AOP is less complex to use than AspectJ in light of the fact that we don't have to stress over the weaving process.
    • Spring AOP underpins AspectJ comments, so on the off chance that you know about AspectJ, at that point working with Spring AOP is easier.
    • Spring AOP underpins just intermediary based AOP, so it very well may be connected just to strategy execution join focuses. AspectJ bolster a wide range of pointcuts.
    • One of the inadequacy of Spring AOP is that it tends to be connected just to the beans made through Spring Context.
    • What is Spring IoC Container?

      Inversion of Control (IoC) is the component to accomplish free coupling between Objects conditions. To accomplish free coupling and dynamic authoritative of the items at runtime, the articles characterize their conditions that are being infused by other constructing agent objects. Spring IoC compartment is the program that infuses conditions into an item and make it prepared for our use.

      Spring Framework IoC compartment classes are a piece of org.springframework.beans and org.springframework.context bundles and gives us diverse approaches to decouple the item dependencies.

      Some of the helpful ApplicationContext executions that we use are;

      • AnnotationConfigApplicationContext: For independent java applications utilizing comments based configuration.
      • ClassPathXmlApplicationContext: For independent java applications utilizing XML based configuration.
      • FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext with the exception of that the xml arrangement record can be stacked from anyplace in the document system.
      • AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.

    • What is a Spring Bean?

      Any typical java class that is introduced by Spring IoC compartment is called Spring Bean. We use Spring ApplicationContext to get the Spring Bean occurrence.

      Spring IoC compartment deals with the existence cycle of Spring Bean, bean scopes and infusing any required conditions in the bean.

    • What is the significance of Spring bean arrangement file?

      We use Spring Bean arrangement document to characterize every one of the beans that will be introduced by Spring Context. When we make the occasion of Spring ApplicationContext, it peruses the spring bean xml record and introduce every one of them. When the setting is introduced, we can utilize it to get diverse bean instances.

      Apart from Spring Bean setup, this document additionally contains spring MVC interceptors, see resolvers and different components to help comments based configurations.

    • What are diverse approaches to arrange a class as Spring Bean?

      There are three diverse approaches to arrange Spring Bean.

      1. XML Configuration: This is the most mainstream design and we can utilize bean component in setting document to arrange a Spring Bean. For instance:
        <bean name="myBean" class="com.journaldev.spring.beans.MyBean"></bean> 
      2. Java Based Configuration: If you are utilizing just explanations, you can design a Spring bean utilizing @Bean comment. This explanation is utilized with @Configuration classes to arrange a spring bean. Test setup is:
        public class MyConfiguration { 
        public MyService getService(){ 
        return new MyService(); 

        To get this bean from spring setting, we have to utilize following code snippet:

        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( 
        MyService administration = ctx.getBean(MyService.class); 
      3. Annotation Based Configuration: We can likewise utilize @Component, @Service, @Repository and @Controller comments with classes to design them to be as spring bean. For these, we would need to give base bundle area to examine for these classes. For instance:
        <context:component-filter base-package="com.journaldev.spring"/> 
    • What are distinctive extents of Spring Bean?

      There are five degrees characterized for Spring Beans.

      singleton: Only one occurrence of the bean will be made for every holder. This is the default scope for the spring beans. While utilizing this extension, ensure spring bean doesn't have shared occurrence factors else it may prompt information irregularity issues since it's not string safe.

      prototype: another case will be made each time the bean is requested.
    • request: This is same as model extension, anyway it's intended to be utilized for web applications. Another occurrence of the bean will be made for every HTTP request.
    • session: another bean will be made for every HTTP session by the container.
    • global-session: This is utilized to make worldwide session beans for Portlet applications.

Spring Framework is extendable and we can make our very own extensions as well, anyway the greater part of the occasions we are great with the degrees given by the framework.

To set spring bean scopes we can utilize "scope" trait in bean component or @Scope comment for comment based setups.

  • What is Spring Bean life cycle?

    Spring Beans are instated by Spring Container and every one of the conditions are additionally infused. At the point when setting is devastated, it likewise pulverizes all the instated beans. This functions admirably in the majority of the cases yet once in a while we need to instate different assets or do some approval before making our beans prepared to utilize. Spring structure offers help for post-instatement and pre-pulverize techniques in spring beans.

    How to get ServletContext and ServletConfig object in a Spring Bean?

    There are two different ways to get Container explicit items in the spring bean.

    What is Bean wiring and @Autowired annotation?

    The procedure of infusion spring bean conditions while instating it called Spring Bean Wiring.

    Usually it's best practice to do the unequivocal wiring of all the bean conditions, however spring structure additionally underpins autowiring. We can utilize @Autowired comment with fields or strategies for autowiring byType. For this comment to work, we additionally need to empower explanation based arrangement in spring bean setup record. This should be possible by context:annotation-config element.

    What are distinctive sorts of Spring Bean autowiring?

    There are four sorts of autowiring in Spring framework.

    1. autowire byName
    2. autowire byType
    3. autowire by constructor
    4. autowiring by @Autowired and @Qualifier annotations
    5. Does Spring Bean give string safety?

      The default extent of Spring bean is singleton, so there will be just a single occurrence for every unique situation. That implies that all the having a class level variable that any string can refresh will prompt conflicting information. Henceforth in default mode spring beans are not string safe.

      However we can change spring bean extension to demand, model or session to accomplish string wellbeing at the expense of execution. It's a structure choice and dependent on the venture necessities.

    6. What is a Controller in Spring MVC?

      Just like MVC configuration design, Controller is the class that deals with all the customer asks for and send them to the arranged assets to deal with it. In Spring MVC, org.springframework.web.servlet.DispatcherServlet is the front controller class that instates the setting dependent on the spring beans configurations.

      A Controller class is dependable to deal with various sort of customer demands dependent on the demand mappings. We can make a controller class by utilizing @Controller comment. Typically it's utilized with @RequestMapping explanation to characterize handler strategies for explicit URI mapping.

    7. What's the distinction between @Component, @Controller, @Repository & @Service comments in Spring?

      @Component is utilized to show that a class is a part. These classes are utilized for auto location and designed as bean, when explanation based arrangements are utilized.

      @Controller is a particular kind of segment, utilized in MVC applications and generally utilized with RequestMapping annotation.

      @Repository explanation is utilized to demonstrate that a segment is utilized as vault and a system to store/recover/seek information. We can apply this comment with DAO design execution classes.

      @Service is utilized to demonstrate that a class is a Service. Normally the business exterior classes that furnish a few administrations are clarified with this.

      We can utilize any of the above explanations for a class for auto-identification however extraordinary sorts are given so you can undoubtedly recognize the motivation behind the commented on classes.

    8. What is DispatcherServlet and ContextLoaderListener?

      DispatcherServlet is the front controller in the Spring MVC application and it stacks the spring bean arrangement record and introduce every one of the beans that are designed. In the event that comments are empowered, it likewise examines the bundles and design any bean explained with @Component, @Controller, @Repository or @Service annotations.

      ContextLoaderListener is the audience to fire up and shut down Spring's root WebApplicationContext. It's vital capacities are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to robotize the making of ApplicationContext. We can utilize it to characterize shared beans that can be utilized crosswise over various spring contexts.

    9. What is ViewResolver in Spring?

      ViewResolver usage are utilized to determine the view pages by name. Generally we arrange it in the spring bean design document. For example:

      <!- - Resolves sees chose for rendering by @Controllers to .jsp assets in the/WEB-INF/sees registry - > 
      <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
      <beans:property name="prefix" value="/WEB-INF/sees/"/> 
      <beans:property name="suffix" value=".jsp"/> 

      InternalResourceViewResolver is one of the execution of ViewResolver interface and we are giving the view pages catalog and addition area through the bean properties. So if a controller handler technique returns "home", see resolver will utilize see page situated at /WEB-INF/sees/home.jsp.

    10. What is a MultipartResolver and when its used?

      MultipartResolver interface is utilized for transferring documents – CommonsMultipartResolver and StandardServletMultipartResolver are two executions given by spring structure to record transferring. Of course there are no multipart resolvers arranged however to utilize them for transferring records, all we have to characterize a bean named "multipartResolver" with sort as MultipartResolver in spring bean configurations.

      How to make ApplicationContext in a Java Program?

      There are following approaches to make spring setting in an independent java program.

      1. AnnotationConfigApplicationContext: If we are utilizing Spring in independent java applications and utilizing explanations for Configuration, at that point we can utilize this to introduce the holder and get the bean objects.
      2. ClassPathXmlApplicationContext: If we have spring bean setup xml document in independent application, at that point we can utilize this class to stack the record and get the holder object.
      3. FileSystemXmlApplicationContext: This is like ClassPathXmlApplicationContext with the exception of that the xml design document can be stacked from anyplace in the record system.
    11. Can we have different Spring arrangement files?

      For Spring MVC applications, we can characterize different spring setting arrangement records through contextConfigLocation. This area string can comprise of various areas isolated by any number of commas and spaces. For example;


      We can likewise characterize various root level spring arrangements and burden it through setting param. For example;


      Another alternative is to utilize import component in the setting arrangement document to import different setups, for example:

      <beans:import resource="spring-jdbc.xml"/> 
    12. What is ContextLoaderListener?

      ContextLoaderListener is the audience class used to stack root setting and characterize spring bean arrangements that will be obvious to every other setting. It's designed in web.xml document as:

    13. What are the base arrangements expected to make Spring MVC application?

      For making a straightforward Spring MVC application, we would need to do following tasks.

      • Add spring-context and spring-webmvc conditions in the project.
      • Configure DispatcherServlet in the web.xml document to deal with solicitations through spring container.
      • Spring bean design record to characterize beans, on the off chance that utilizing explanations, at that point it must be arranged here. Likewise we have to arrange see resolver for view pages.
      • Controller class with demand mappings characterized to deal with the customer requests.
    14. Above steps ought to be sufficient to make a straightforward Spring MVC Hello World application.

    15. How would you relate Spring MVC Framework to MVC architecture?

      As the name proposes Spring MVC is based over Model-View-Controller engineering. DispatcherServlet is the Front Controller in the Spring MVC application that deals with all the approaching solicitations and representative it to various controller handler methods.

      Model can be any Java Bean in the Spring Framework, much the same as some other MVC system Spring gives programmed official of structure information to java beans. We can set model beans as credits to be utilized in the view pages.

      View Pages can be JSP, static HTMLs and so on and see resolvers are in charge of finding the right view page. When the view page is distinguished, control is offered back to the DispatcherServlet controller. DispatcherServlet is in charge of rendering the view and restoring the last reaction to the customer.

    16. How to accomplish limitation in Spring MVC applications?

      Spring gives amazing help to confinement or i18n through asset groups. Premise steps expected to make our application limited are:

      1. Creating message asset packs for various regions, for example, messages_en.properties, messages_fr.properties etc.
      2. Defining messageSource bean in the spring bean arrangement document of sort ResourceBundleMessageSource or ReloadableResourceBundleMessageSource.
      3. For change of area support, characterize localeResolver bean of sort CookieLocaleResolver and arrange LocaleChangeInterceptor interceptor. Model arrangement can resemble beneath:
        <beans:bean id="messageSource" 
        <beans:property name="basename" value="classpath:messages"/> 
        <beans:property name="defaultEncoding" value="UTF-8"/> 
        <beans:bean id="localeResolver" 
        <beans:property name="defaultLocale" value="en"/> 
        <beans:property name="cookieName" value="myAppLocaleCookie"></beans:property> 
        <beans:property name="cookieMaxAge" value="3600"></beans:property> 
        <beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> 
        <beans:property name="paramName" value="locale"/> 
      4. <beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <beans:property name="basename" value="classpath:messages"/> <beans:property name="defaultEncoding" value="UTF-8"/> </beans:bean> <beans:bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> <beans:property name="defaultLocale" value="en"/> <beans:property name="cookieName" value="myAppLocaleCookie"></beans:property> <beans:property name="cookieMaxAge" value="3600"></beans:property> </beans:bean> <interceptors> <beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <beans:property name="paramName" value="locale"/> </beans:bean> </interceptors>

        How would we be able to utilize Spring to make Restful Web Service returning JSON response?

        <!- - Jackson - > <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.databind-version}</version> </dependency>
      5. Configure RequestMappingHandlerAdapter bean in the spring bean setup record and set the messageConverters property to MappingJackson2HttpMessageConverter bean. Test design will be:
        <!- - Configure to module JSON as demand and reaction in strategy handler - > <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <beans:property name="messageConverters"> <beans:list> <beans:ref bean="jsonMessageConverter"/> </beans:list> </beans:property> </beans:bean> <!- - Configure bean to change over JSON to POJO and the other way around - > <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> </beans:bean>
      6. In the controller handler techniques, return the Object as reaction utilizing @ResponseBody explanation. Test code:
        @RequestMapping(value = EmpRestURIConstants.GET_EMP, technique = RequestMethod.GET) 
        public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) { 
        logger.info("Start getEmployee. ID="+empId); 
        return empData.get(empId); 

        Can we send an Object as the reaction of Controller handler method?

        Yes we can, utilizing @ResponseBody explanation. This is the way we send JSON or XML based reaction in serene web services.

        How to utilize Tomcat JNDI DataSource in Spring Web Application?

        For utilizing servlet holder designed JNDI DataSource, we have to arrange it in the spring bean setup document and afterward infuse it to spring beans as conditions. At that point we can utilize it with JdbcTemplate to perform database operations.

        Sample design would be:

        <beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> 
        <beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/> 

        How would you accomplish Transaction Management in Spring?

        Spring system gives exchange the executives support through Declarative Transaction Management just as automatic exchange the board. Revelatory exchange the board is most broadly utilized in light of the fact that it's anything but difficult to utilize and works in the vast majority of the cases.

        We use clarify a technique with @Transactional comment for Declarative exchange the board. We have to arrange exchange chief for the DataSource in the spring bean setup file.

        <bean id="transactionManager" 
        <property name="dataSource" ref="dataSource"/> 
      7. What is Spring DAO?

        Spring DAO support is given to work information get to advances like JDBC, Hibernate in a predictable and simple way. For instance we have JdbcDaoSupport, HibernateDaoSupport, JdoDaoSupport and JpaDaoSupport for particular technologies.

        Spring DAO additionally gives consistency in exemption pecking order and we don't have to get explicit exceptions.

      8. How to coordinate Spring and Hibernate Frameworks?

        We can utilize Spring ORM module to incorporate Spring and Hibernate structures, on the off chance that you are utilizing Hibernate 3+ where SessionFactory gives current session, at that point you ought to abstain from utilizing HibernateTemplate or HibernateDaoSupport classes and better to utilize DAO design with reliance infusion for the integration.

        Also Spring ORM offers help for utilizing Spring explanatory exchange the executives, so you ought to use that instead of going for sleep standard code for exchange management.

        How to infuse a java.util.Properties into a Spring Bean?

        We need to characterize propertyConfigurer bean that will stack the properties from the given property document. At that point we can utilize Spring EL backing to infuse properties into other bean conditions. For example;

        <bean id="propertyConfigurer" 
        <property name="location" value="/WEB-INF/application.properties"/> 
        <bean class="com.journaldev.spring.EmployeeDaoImpl"> 
        <property name="maxReadResults" value="${results.read.max}"/> 

        If you are utilizing comment to design the spring bean, at that point you can infuse property like below.

        private int maxReadResults; 

        What are probably the accepted procedures for Spring Framework?

        Some of the prescribed procedures for Spring Framework are:

        1. Avoid form numbers in composition reference, to ensure we have the most recent configs.
        2. Divide spring bean arrangements dependent on their worries, for example, spring-jdbc.xml, spring-security.xml.
        3. For spring beans that are utilized in various settings in Spring MVC, make them in the root setting and introduce with listener.
        4. Configure bean conditions however much as could be expected, endeavor to abstain from autowiring as much as possible.
        5. For application level properties, best methodology is to make a property record and read it in the spring bean setup file.
        6. For littler applications, comments are valuable yet for bigger applications explanations can turn into an agony. In the event that we have all the design in xml records, keeping up it will be easier.
        7. Use right comments for segments for understanding the reason effectively. For administrations use @Service and for DAO beans use @Repository.
        8. Spring system has a ton of modules, use what you need. Evacuate all the additional conditions that gets generally included when you make extends through Spring Tool Suite templates.
        9. If you are utilizing Aspects, make a point to keep the join half quart as tight as conceivable to maintain a strategic distance from counsel on undesirable strategies. Consider custom explanations that are less demanding to utilize and stay away from any issues.
        10. Use reliance infusion when there is genuine advantage, only for free coupling don't utilize it since it's harder to maintain.

  • journaldev is optimized for learning.© journaldev .
    All Right Reserved and you agree to have read and accepted our term and condition