Friday, 5 February 2016

Spring All

1. What is spring ? Why use spring ?
2. What is IoC ? What is DI ? Types of DI ? When to use which ?
3. What are the modules in spring ?
4. What is AOP ? Why use it ?
5. What is spring MVC? How to setup spring mvc?
6. What is lifecycle of bean?
7. What is beanfactory and application context? Differences?
8. What are scopes of bean in spring ? Differences?
9. Which design patters are used in spring?
10. What are the new features in spring 4?
11. What is bean auto wiring? What are different types of doing that?
12. How will you resolve circular dependency in spring?
13. What is aspect, joinpoint, pointcut, advice, introduction, target?
14. What is weaving? Types?
15. how to integrate hibernate with spring?
16. How to inject list? 
17. how to develop rest web services in spring?
18. What are best practices in spring?
19. What is the difference between n-tier and MVC?
20. How is transaction management done in spring? Types? Prefer?
21. Design patterns used in spring?
22. What is dispatcher servlet?
23. Difference between @Component, @Repository, @Service ?
24. Types of IoC container in spring ? Differences ?
25. Spring AOP vs aspectJ AOP ?
26. How to handle exceptions in spring  , spring mvc  , sprin jdbc , etc?
27. Does spring bean provide thread safety ?
28. Can we have multiple spring configuration files?
29. What is spring xml based configuration and java based configuration and annotation based? Difference? Which one you prefer and use?
30. Are singleton beans thread safe ?
31. How to inject collections?
how spring simplifies jdbc ?
How validation in spring ?
What are different implementation/types of ApplicationContext ?
all the annotations in spring.
what are the annotation in spring rest?
what are common implementations of applicationContext?
What are exceptions thrown by spring dao?
Different jdbc template? purpose?
23. does spring framework supports all join points ?
24. what is front controller class in spring mvc
25. @Controller
26. @RequestMapping
27. @PathVariable
28. ViewResolver ? Types ?
31. Benefits of spring tool suite ?
32. What is spring bean ?
33. Different ways of configuring spring bean ?
35. what is context loader listener ?
36. what is multipart resolver and when it's used ?
40. what is spring mvc interceptor ?
41. what is spring security ?
42. how to inject properties ?
48. Explain @Autowired
49. Explain @Qualifier
50. Explain @Inject
51. Explain @Required
52. DIfferent types of events in spring ?
53. Difference between FileSystemResource , ClassPathREsource
57. what are inner beans ?
58. what are limitations in autowiring ?
59. how to turn on annotation wiring ?
60. what is spring dao ? (??)
61. spring aop target object ?
can there be more than one dispatcher servlet?
is it possible to have single  context(root) for single dispatcher servlet.(yes)
**********unranked ends**************
Spring Top 10
1. What is spring ? Why use spring ?
Spring is an Inversion of Control and Aspected Oriented Programming based container framework.
Spring provides a lot of benefits:
a) Loosely coupled code: Since spring is IoC based it enforces loosely coupled code which has many benefits. Loosely coupled is easy to modify and test.
b) Reduces boilerplate code: Spring provides a lot of templates such as JdbcTemplate, HibernateTempleate which reduces a lot of boilerplate code.
c) Better Exception Handling: Spring has converted a lot of checked exceptions to unchecked and more meaningful exceptions.
d) Lightweight: Spring is very lightweight and has no additional overhead.
e) Provides integration with most of the major frameworks such as jdbc,hibernate,ibatis,struts,etc.
f) It provides support for web applications through spring MVC and support for developing rest web services.
g) Non-Invasive:
2. What is IoC? What is DI? Types of DI? When to use which?
IoC stands for Inversion of Control. It refers to the change in program control flow from the code to some external entity. It leads to loosely coupled code which is easy to maintain,extend and test.
IoC can be achieved in various ways:
a) By factoy design pattern
b) By dependency injection
c) By interface injection
Spring uses dependency injection to achieve Inversion of control. DI is of two types:
a) Constructor based: For mandatory values
b) Setter based: For optional values.
3. What are the modules in spring?
Spring has around 20 modules which are categorised in 6 groups:
a) Test : Support for unit testing such as jUnit.
b) Core Container
i),ii) Core and Beans : IoC container. BeanFactory
iii) Context : ApplicationContext extends BeanFacotry and provides additional features such as internationalization , beans lifecycle events , etc.
iv) Expression Language: Provides powerful language to query and modify objects at runtime.
c) AOP  and Aspects : Provide Aspect Oriented Programming support to Spring.
d) Instrumentation
e) Data Access/Integration:
ii) ORM
iii) OXM
iv) JMS
v) Transactions:
f) Web
i) Web
ii) Servlet
iii) Portlet
iv) Struts
4. What is AOP? Why use it?
AOP stands for Aspect Oriented Programming. It is a programming paradigm which modularize/encapsulate cross-cutting behaviour in an application. Benefits:
a) Modularization of cross-cutting behaviour, thus all the scattered code is at one place which is easy to modify.
b) Clear seperation of concerns.
c) In case when we don't have access to source code, we can implement new functionality.
5. What is spring MVC ? Benefits?
Spring Doc Figure for MVC
Spring provides MVC framework for web applications. MVC is a design patterns which provides seperation of roles among data, front end and business logic in an n-tier application.
mvc context hierarchy
Spring context heirarchy
Java4S Figure shows MVC Flow
Figure taken from DZone shows MVC Flow
Flow:1. Request comes to the Dispatcher Servlet. Dispatcher Servlet uses Handler Mapping and forwards the request to appropriate Controller.
2. The Controller calls the appropriate service methods which interacts with the model and create a ModelAndView object containing model data and view name and return it to Dispatcher Servlet.
3. Dispatcher Servlet passes the view name to View Resolver which returns the actual view.
4. Dispatcher Servlet passes the model data to View which renders the response and return the control to Dispatcher Servlet.

a) Clean separation of roles: All the components have clear seperation of roles, thus it's easy to modify.
a) Modular design: All the components are loosely coupled and can be easily replaced.
Spring MVC sample application developed using STS : Download
6. What is lifecycle of bean?
a) Bean is intialized
b) If implements BeanNameAware , name is set.
c) If implements BeanFactory , (?)
d) If implements BeanPostProcessor , initalize method
e) init method
f)  If implements BeanPostProcessor , destroy method
g) destroy method
7. What is beanfactory and application context? Differences?
BeanFacotory provides IoC.
ApplicationContext extends BeanFactory and provides a lot of additional benefits in a web application such as internationalization, handling bean life cycle events, reading properties, etc.
8. What are scopes of bean in spring ? Differences ?
There are five types of scopes of bean in spring:
a) Singleton: Default , one object
b) Prototype:
c) Request :
e) Global : Lifetime of application
c,d,e for web application.
9. Which design patterns are used in spring ?
a) MVC : Spring MVC
b) Front Controller design pattern: Spring MVC
c) Singleton: bean scopes
d) Prototype: bean scopes
e) Factory, Inversion of Control: BeanFactory and Application Context
f) Proxy
g) Template
10. What are the new features in spring 4?
a) Web Socket: duplex communication
b) Java 8 support
c) Getting current session of hibernate
d) Setting profiles
e) A lot of minor improvements
11. What is bean auto wiring? What are different types of doing that?
Bean auto-wiring is automatic configuration of beans in spring. There are different ways of doing it:
a) Name
b) Type
c) Constructor
Auto-detect(Deprecated in Spring 3)
12. How will you resolve circular dependency in spring?
We'll use setter injection in this case. Spring can resolve circular dependency
13. What is aspect, joinpoint, pointcut, advice, introduction, target?
Aspect: Aspect is the concern.
Joinpoint: The point at which new functionality has to be introduced.
Pointcut: Set of all the joinpoints where a particular functionality is to be introduced.
Advice: The functionality which is to be introduced.
Introduction: New method which is to be added to a code.
Target: The target class or code.
14. What is weaving? Types?
The process of modification of the existing code to introduce the new functionality by aop is called weaving.
a)Compile time:
b)Classload time:
15. How to integrate hibernate with spring?
Download sample project.

16. How to inject list? 
List example:

17. how to develop rest web services in spring?
1. Generate spring MVC using STS.
2. Add the following dependency in pom.xml
 jackson json dependency here
It will automatically convert the POJO to json object.
3. Change the annotation @Controller to @RestController.
Sample Project Example using Spring4(STS) : Download
18. What are best practices in spring? a) Naming convention: Use proper naming convention. b) Avoid overuse of autowiring. c) Logging: Use SLF4J. Avoid others. Avoid printing to console. d) Unit Testing: Use spring unit testing support. e) Don't put version number in xml schemas. f) Prefer setter injection over constructor injection. g) Always externalize values,constants.
19. What is the difference between n-tier and MVC? N-tier refers to the different layers in an architecture which are in a linear way such as the application layer depends on business layer which in turns depends on database layer. These are build on top of each other. MVC, on the other hand, is clear seperation of roles and there is traingular way of interaction between the three.
20. How is transaction management done in spring? Types? Prefer? Declarative transaction management: By annotations
Programmatic transaction management: By code
Spring AOP:
Less powerful than AspectJ
Can call on method only, not fields
Can call on classes having interface
To call on classes without interface, use cglib dependency
You can call aop only on spring managed beans.
<aop:aspectj-autoproxy /> is required to enable aop
Beans of aspect must be created
Bean of target object also must be created

package com.mkyong.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

public class LoggingAspect {

 //Interface based 
 public void logBefore(JoinPoint joinPoint) {

  System.out.println("logBefore() is running!");
  System.out.println("hijacked : " + joinPoint.getSignature().getName());
 @Before("execution (public void pack.Dog.speak())")
 public void beforeDog(){
  System.out.println("Dog getting angry..");
 //Getting arguments , via args and joinpoint
 @Before("execution (public void pack.Dog.listen(..)) && args(str,..))")
 public void beforeListen(JoinPoint joinPoint,String str){
  System.out.println("Dog is going to listen this:"+str);
  System.out.println("Via JoinPoint:"+ joinPoint.getArgs()[0]);
 @Before("execution (public void")
 public void beforeDog(JoinPoint joinPoint){
  System.out.println("This object:"+joinPoint.getThis());
 @After("execution (public void pack.Dog.speak())")
 public void afterDog(){
  System.out.println("Dog cooling down");
 //This works but won't work correctly when method is returning a value
 @Around("execution (public void pack.Dog.speak())")
 public void aroundDog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
  System.out.println("Before around");
  System.out.println("After around");
 @Around("execution (public String pack.Dog.getBone())")
 public Object aroundDogBone(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
  System.out.println("Before around dog bone");
  Object obj = proceedingJoinPoint.proceed();
  System.out.println("After around dog bone");
  return obj;
 @AfterReturning("execution (public void pack.Dog.speak())")
 public void afterReturningDog(){
  System.out.println("after returning");
 @AfterThrowing("execution (public void pack.Dog.speak(..))")
 public void afterThrowingDog(){
  System.out.println("after throwing");


Spring Transaction
Create datasource
Create sessionfactory using datasource , hibernate4sessionfactorylocalbean..
Create spring transaction manager
For transaction use hibernate getCurrentSession
Hibernatetemplate is no more used
Declarative and programmatic transaction, declarative is preferred
hibernate session flush is necessary sometimes
getCurrentSession will work only with transaction, session using this shouldn't be closed.
<tx:annotation-driven/> is required to enable annotation support for transaction
OR use @EnableTransactionManagement

Name in href for jsp should be without .jsp.

Spring Validation
Uses hibernate validation
@Valid to put on model object
Errors will come in BindingResult object.
Add @ModelAttribute and define a method
In jsp file , use spring form taglib and create a form, give path to each field, and give commandName same as @ModelAttribute and pass it in method, define form:error and cssClass to display the error.

Spring Exception Handling
@ExceptionHandler(Exception.class) annotation on a method in the controller file will enable the method to handle that type of exception
Define a class and makr it with @ControllerAdvice to make it global exception handler, inside it same as first point
Also, set response status with error code with message,
Also, define the error pages in web.xml(??)

Spring interceptor
Filter vs interceptor, Filter is more powerful but limited to request and response, interceptor can be used ........
Interceptor can be created by implementing interface HandlerInterceptor or extending class HandlerInterceptorAdapter
Methods to implement , preHandle, postHandle , afterCompletion

Spring Security
Need to include two jars , spring-security-config, spring-security-web

No comments:

Post a Comment