Most Common Spring Interview Questions : This blog is just for a revision .
2.
private ServletContext context;
public void setServletContext(ServletContext servletContext) {
this.context = servletContext;
}
Methods :
- What is dependency injection ?
- Constructor constructor-arg : for mandatory dependencies
- Setter ref : for optional dependencies
- using @Autowired
- Types of IoC container?
- BeanFactory
- ApplicationContext
- What are the advantages of ApplicationContext?
- Internationalization
- Annotation support
- Load all beans on start
- lazy-init for lazy loading
- No need to register AutowiredBeanPostProcessor
- Automatic BeanPostProcessor , BeanFactoryPostProcessor registration
- Easy MessageSource access (for i18n)
- ApplicationEvent publication
- Advantages of spring IoC ?
- Less code
- Easy testing
- Loose coupling
- Lazy loading
- What is spring bean ?
- Explain Spring bean life cycle.
- Check the configuration
- Initialization
- Dependency Injection
- set bean name
- set bean class loader
- set bean factory
- set resource loader
- set application event publisher
- set message source
- set Application Context
- set Servlet context
- postProcessBeforeInitialization
- afterPropertiesSet
- init method
- postProcessAfterInitialization
- destroy
- destroy
- Explain scope of bean .
- singleton : default , one instance in the container
- prototype : new instance every time the getBean is called
- request : one bean for life cycle of http request
- session : one bean for life cycle of http session
- global session : one bean for life cycle of ServletContext
- What is BeanPostProcessor ?
- postProcessBeforeInitialization before init method
- postProcessAfterInitialization after init method
- How to create ApplicationContext ?
- XML based :ClassPathXmlApplicationContext("xml file")
- Annotation based : in web-servlet.xml use <context:component-scan base-package= > .
- Java based : @Configuration , @Bean , @Scope, @Import , @ComponentScan
- Explain JSR 250 annotations used in spring .
- @PostConstruct : alternative to init
- @PreDestroy : alternative to destroy
- @Resource(name ="") : similar to @Autowired @Qualifier("")
- Explain other annotations in spring to be used with annotation based configuration
- @Required:applied on setter , the value should be provided in xml
- @Component parent of annotations
- @Controller ,
- @Repository ,
- @Service
- Explain Autowiring .
- no : explicit bean references
- byName : by the bean name in xml file.
- byType : matches the type of the bean
- contructor : check the type of the parameter in constructor
- Explain inner bean
- What are the new features in Spring 4 .
- Added path to RequestMapping
- MVC test framework
- @RestController and AsyncRestTemplate is used.
- instread of response it returns ListenableFuture
- uses java 8 , minimum requirement is Java 6.
- define external bean configuration using a Groovy
- Added @Description
- @Lazy can be used in bean injection and definition .
- @Autowired @Value can be used as meta annotations
- Introduced ordering for autowired , using @Order and Ordered interface .
- @Bean in @Configuration Class
- Conditional filtering of beans added for @Conditional .
- Generic type as qualifier for injecting bean
- create custom annotation to expose attribute of the source annotation .
- New features added in Spring 5.
- bean scopes : singleton, prototype , request , session , application , websocket (one bean for lifecycle of Websocket )
- Explain the components of Spring MVC.
- Dispatcher Servlet
- Handler Mapping
- Controller
- Model And View
- View Resolver
- View
- Explain Dispatcher Servlet
entry added in web.xml for dispatcher servlet
- org.springframework.web.servlet.DispatcherServlet
- loadOnStartUp = 1
Create {servlet-name}-servlet.xml,specify
Dispatcher servlet checks with handler mapping and redirects to the appropriate controller .
- 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 ?
- InternalResourceViewResolver : based on URL , suffix and prifix
- XmlViewResolver : view definition in a dedicated XML .
- 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.
1.
@Autowired
ServletContext context;
2.
private ServletContext context;
public void setServletContext(ServletContext servletContext) {
this.context = servletContext;
}
Methods :
- getInitParameter () : returns value set in <context-param> <param-name>
- What is servletConfig?
One per servlet
gets notified when servlet context is initialized or destroyed .
To customise web MVC configuration.
Like add view controller
View resolver in java code .
used to configure servlet context programmatically , used as an alternative to configuration in web.xml
If we want enable a bean only during development and not in production we can assign the profile to the bean , using @Profile("dev")
- getInitParameter(String name): returns value set in <init-param><name>
- getInitParameterNames(): returns all <init-param>
- getServletContext(): returns ServletContext
- 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?
- @Controller : class is a web request handler
- @Component : auto-detection when using annotation-based
- @RestController = @Controller + @ResponseBody
- @RequestMapping method: get/put value : URL
- @PathVariable input in request URL.
- @RequestParam input in url with ?id=
- @Transactional : can be applied to class or method.
- @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
- use CommonsMultipartResolver add dependency commons-fileupload
- add bean configuration in servlet-config.xml file
- "multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
- input type = file in html
- @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 ?
- Set the servlet context init Param using WebApplicationInitializer
- Set context Param in web.xml
- Set the JVM system parameter
- Set the environment variable
- Set in maven profile
- Configurable environment set active profile
- Explain spring events
- event class should extend ApplicationEvent
- publish event can be done using applicationEventPublisher.publishEvent(customSpringEvent);
- listener has to implement ApplicationListener<MyEvent>
- listener need to override onApplicationEvent(MyEvent myEvent)
- What are the events related to ApplicationContext
- ContextRefreshedEvent
- ContextStartedEvent
- ContextStoppedEvent
- ContextClosedEvent
- What is Join Point ?
- method called
- state changed
- exception occurred
- What is an Point Cut ?
an expression
- What is an advice ?
Action taken (method ).
- before
- after
- around : decides whether the method gets executed or not
- afterReturning :executed only if method executed successfully .
- afterThrowing : executed only if exception is occurred during method execution .
- What is aspect ?
class that implements cross cutting concerns .
adds production grade services to the application
- logging
- security
- transaction management
- exception handling
- performance testing
- What is weaving?
- What is proxy?
- What are the features of spring boot?
- Auto configuration : configure beans based on the jar available at classpath and beans used in the project . Annotations used : @ConditionalOnClass, @ConditionalOnMissingBean .
- Starters project
- Cli using groovy
- Actuator
- Initializer
- Explain Spring Boot Annotations
- @SpringBootApplication
- @EnableAutoConfiguration
- What is Spring Boot Initilizr ?
- What is Spring Boot Actuator
- info
- health : up
- trace
- 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