Sunday, March 17, 2019

Spring Interview Question

Most Common Spring Interview Questions : This blog is just for a revision .


  • What is dependency injection ?
Spring IoC container takes care of object creation and wiring them together.
  1. Constructor constructor-arg : for mandatory dependencies
  2. Setter ref : for optional dependencies
  3. using @Autowired
  • Types of IoC container?
  1. BeanFactory
  2. ApplicationContext
  • What are the advantages of ApplicationContext?
  1. Internationalization
  2. Annotation support
  3. Load all beans on start 
  4. lazy-init for lazy loading
  5. No need to register AutowiredBeanPostProcessor
  6. Automatic BeanPostProcessor , BeanFactoryPostProcessor registration
  7. Easy MessageSource access (for i18n)
  8. ApplicationEvent publication
  • Advantages of spring IoC ?
  1. Less code
  2. Easy testing
  3. Loose coupling
  4. Lazy loading
  • What is spring bean ?
java class created by spring IoC container .
  • Explain Spring bean life cycle.
  1. Check the configuration
  2. Initialization
  3. Dependency Injection
  4. set bean name
  5. set bean class loader
  6. set bean factory
  7. set resource loader
  8. set application event publisher
  9. set message source 
  10. set Application Context
  11. set Servlet context
  12. postProcessBeforeInitialization
  13. afterPropertiesSet
  14. init method
  15. postProcessAfterInitialization
  16. destroy
  17. destroy
  • Explain scope of bean .
  1. singleton : default , one instance in the container 
  2. prototype : new instance every time the getBean is called
  3. request : one bean for life cycle of http request 
  4. session : one bean for life cycle of http session
  5. global session : one bean for life cycle of ServletContext
  • What is BeanPostProcessor ?
implementation can define a callback method .
  1. postProcessBeforeInitialization  before init method
  2. postProcessAfterInitialization after init method
  • How to create ApplicationContext ?
  1. XML based :ClassPathXmlApplicationContext("xml file")
  2. Annotation based : in web-servlet.xml use  <context:component-scan base-package= > .
  3. Java based :  @Configuration ,  @Bean , @Scope, @Import , @ComponentScan
  • Explain  JSR 250  annotations used in spring .
  1. @PostConstruct : alternative to init 
  2. @PreDestroy : alternative to destroy
  3. @Resource(name ="")   : similar to @Autowired @Qualifier("") 
  • Explain other annotations in spring to be used with annotation based configuration
  1. @Required:applied on setter , the value should be provided in xml 
  2. @Component parent of annotations
    • @Controller , 
    • @Repository , 
    • @Service 
  •  Explain Autowiring .
Enables us to inject dependency implicitly, using autowire in xml
  1. no : explicit bean references 
  2. byName : by the bean name in xml file.
  3. byType : matches the type of the bean 
  4. contructor : check the type of the parameter in constructor 
  • Explain inner bean 
A bean used as property of another bean . A <bean> inside <property> .
  • What are the new features in Spring 4 .
  1. Added path to RequestMapping
  2. MVC test framework
  3. @RestController and AsyncRestTemplate is used.
  4. instread of response it returns ListenableFuture 
  5. uses java 8 , minimum requirement is Java 6.
  6. define external bean configuration using a Groovy
  7. Added @Description
  8. @Lazy can be used in bean injection and definition .
  9. @Autowired @Value can be used as meta annotations
  10. Introduced ordering for autowired , using @Order and Ordered interface .
  11. @Bean in @Configuration Class
  12. Conditional filtering of beans added for @Conditional .
  13. Generic type as qualifier for injecting bean
  14. create custom annotation to expose attribute of the source annotation .
  • New features added in Spring 5.
  1. bean scopes : singleton, prototype , request , session , application , websocket (one bean for lifecycle of Websocket )


  • Explain the components of Spring MVC.
  1. Dispatcher Servlet
  2. Handler Mapping
  3. Controller
  4. Model And View
  5. View Resolver
  6. View
  • Explain Dispatcher Servlet
Front Controller for all incoming Request.
entry added in web.xml for dispatcher servlet
    • org.springframework.web.servlet.DispatcherServlet
    • loadOnStartUp = 1
Create {servlet-name}-servlet.xml,specify

    • context:component-scan
    • mvc:annotation-driven



  • What is handler mapping

Dispatcher servlet checks with handler mapping and  redirects to the appropriate controller .


  • What is view resolver ?
It determines the view to which the request has to be transferred .

  1. InternalResourceViewResolver : based on URL , suffix and prifix
  2. XmlViewResolver : view definition in  a dedicated XML .
  3. ResourceBundleViewResolver : view definition in a property file .




    • What is ServletContext ?
    One per application , created once the web application is deployed .
    To access in spring context , the controller must implement ServletContextAware   ,add either of the following code  
    1. 
    @Autowired
    ServletContext context; 

    2.
    private ServletContext context;

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

    Methods :

    1. getInitParameter () : returns value set in <context-param> <param-name>
    • What is servletConfig?
    One per servlet

    1. getInitParameter(String name): returns value set in <init-param><name>  
    2. getInitParameterNames(): returns all <init-param>
    3. getServletContext(): returns ServletContext
    4. getServletName(): returns value set in <servlet><servlet-name>


    • What is servlet context listener ?

    gets notified when servlet context is initialized or destroyed .
    • Explain  Spring MVC annotations?
    1. @Controller : class is a web request handler 
    2. @Component : auto-detection when using annotation-based 
    3.  @RestController = @Controller + @ResponseBody
    4. @RequestMapping method: get/put value : URL
    5. @PathVariable input in request URL.
    6. @RequestParam input in url with ?id=
    7. @Transactional : can be applied to class or method.
    8. @EnableWebMvc enable spring MVC through java configuration.

    • What is WebMvcConfigurer .

    To customise web MVC configuration.
    Like add view controller
    View resolver in java code .


    • What is WebApplicationInitializer

    used to configure servlet context programmatically , used as an alternative to configuration in web.xml


    • Explain file upload in spring 
    1. use CommonsMultipartResolver add dependency commons-fileupload
    2. add bean configuration in servlet-config.xml file 
      • "multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
    3. input type = file in html
    4. @RequestParam MultipartFile
    • What is a profile

    If we want enable a bean only during development and not in production we can assign the profile to the bean , using @Profile("dev")

    • How to declare a profile ?
    1. Set the servlet context init Param using WebApplicationInitializer
    2. Set context Param in web.xml
    3. Set the JVM system parameter
    4. Set the environment variable
    5. Set in maven profile
    6.  Configurable environment set active profile
    • Explain spring events 
    1. event class should extend ApplicationEvent
    2. publish event can be done using applicationEventPublisher.publishEvent(customSpringEvent);
    3. listener has to implement ApplicationListener<MyEvent>
    4. listener need to override onApplicationEvent(MyEvent myEvent)
    • What are the events related to ApplicationContext
    1. ContextRefreshedEvent
    2. ContextStartedEvent
    3. ContextStoppedEvent
    4. ContextClosedEvent
    • What is Join Point ?
    An event occurred during the execution of a program.
    1. method called 
    2. state changed
    3. exception occurred 
    • What is an Point Cut ?
    an expression
    • What is an advice ?
    Action taken (method ).
    1. before
    2. after
    3. around : decides whether the method gets executed or not
    4. afterReturning :executed only if method executed successfully .
    5. afterThrowing : executed only if exception is occurred during method execution .
    • What is aspect ?
    class that implements cross cutting concerns .
    1. logging
    2. security
    3. transaction management
    4. exception handling
    5. performance testing
    • What is weaving?
    Linking aspect with other objects/application types to create adviced object.
    • What is proxy?
    Object created after applying advice to target object.


    • What are the features of spring boot?
    1. Auto configuration : configure beans based on the jar available at classpath  and beans used in the project . Annotations used : @ConditionalOnClass, @ConditionalOnMissingBean .
    2. Starters project
    3. Cli using groovy
    4. Actuator
    5. Initializer

    • Explain Spring Boot Annotations
    1. @SpringBootApplication 
    2. @EnableAutoConfiguration
    • What is Spring Boot Initilizr ?
    It is used to generate a new project .


    • What is Spring Boot Actuator
    adds production grade services to the application

    1. info
    2. health : up
    3. trace
    4. httptrace

    • How do you create Logger in Spring boot .
    org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MyClass.class);
    configure logger level , file path , pattern console profile in application.properties
    create logback.xml



    No comments:

    Post a Comment

    ec2-user@ec2 Permission denied