Basic concepts of Spring

Spring Framework definition/Advantages:
Is an Open source --(anybody can access the spring code and modify) ,
Light weight--------(compared to it's competitors it takes less resourse/memory) ,
Multi-tier Enterprise Application framework(support for all-->struts,hibernate etc.),

It doesn’t force a programmer to extend or implement their class from any predefined class or interface, in struts we used to extend Action Class



What is IoC:
In IOC, control of objects is transferred to container or framework. In IOC objects do not create other objects which they want. Instead, they get the objects that they need from an other source eg. Annotation, xml etc.
eg.@Autowired
private ParameterService parameterService;

What is IOC container:
----------------------------
There are two types of IoC containers.
1)BeanFactory (Interface)
2)ApplicationContext (Interface)

The main tasks performed by IoC container are:

1) IOC container is responsible to --->inject the dependency(Connecting  / Wiring the objects)
2) To instantiate(create an object) the application class
3) To configure the object
4) To assemble the dependencies between the objects
5) DI is same as IOC. DI is a subtype of IOC

Benefits:
----------------
1) Loose coupling
2) Easy to test


BeanFactory vs ApplicationContext:
-------------------------------------------------
1) ApplicationContext extends BeanFactory.
2) Hence BeanFactory provides basic IOC and DI features while ApplicationContext provides advanced features.
3) BeanFactory doesn't provide support for internationalization(display messages, currencies, date, time etc. according to the specific region or language.) i.e. i18n but ApplicationContext provides support for it.




                       --------------- BeanFactory ---------------
                       |                (interface)               |
                       |                                               |
                       | extends                                  | implements
                       |                                              |
                       |                                              |
             ApplicationContext                              XMLBeanFactory(Deprecated)
        (interface)                                      (concrete class)
                       |                   
                       |
               |    implements
               |-------------------ClasspathXmlApplicationContext
               |               (concrete class)
                       |
                       |    implements
                       |-------------------XmlWebApplicationContext
                                             (concrete class)




What is DI (Dependency Injection)?
DI is implementations of IOC through constructors/setters, which the object will 'depend' on in order to behave correctly.
DI  provides loose coupling.

Let's write a code without following DI.
1.    public class Employee{
2.    Address address;
3.    Employee(){
4.    address=new Address();
5.    }
6.    }
Now, there is dependency between Employee and Address because Employee is forced to use the same address instance.

Let's write the DI code.
1.    public class Employee{
2.    Address address;
3.    Employee(Address address){  // constructor injection
4.    this.address=address;//not creating instance
5.    }
6.    }
Now, there is no dependency between Employee and Address because Employee is not forced to use the same address instance.


Dependency injection is classified into 2 categories namely,

1) Constructor Injection
2) Setter Injection

Constructor vs setter injection
------------------------------------
1)In Setter Injection, partial injection of dependencies is possible, means if we have 3 dependencies like int, string, long, then its not necessary to inject all values if we use setter injection.
In constructor injection, partial injection of dependencies is not possible, because for calling constructor we must pass all the arguments

2)Overriding: Setter injection overrides the constructor injection. If we use both constructor and setter injection, IOC container will use the setter injection.

3) Constructor injection will be executed only once

So what should you use?
-----------------------------
-Depends on requirement. We could use combination of both.
-Constructor injection should be used (from spring.io).
-Constructor injection is easy and ensures all mandatory properties have been satisfied since we pass all the arguments when it is called.


Situations in which I would not use constructor injection:
------------------------------------------------------------------
1)Example is a class with a lot of dependencies or other configurable values. Do not consider a constructor with 20 arguments as it is not good coding standard.
2) Refer 1st point of construcor vs setter injection



Annotations:
with @Component, @Repository, @Service @Controller and @RequestController annotations are considered for auto-detection when using annotation-based configuration and classpath scanning. Spring will automatically import the beans into the container. These annotations are called Stereotype annotations as well.

1) @Component
The @Component annotation marks a java class as a bean
eg.
@Component
public class EmployeeDAOImpl implements EmployeeDAO {
    ...
}



2)@Repository (persistence layer)
-The @Repository annotation is a specialization of the @Component annotation with similar use and functionality.

-@Repository provides additional benefits specifically for DAOs

-In addition to importing the DAOs into the DI container, its job is to catch exceptions and re-throw them as one of Spring’s(spring readable) unchecked(run time) exceptions.


3) @Service (used to implement transactions)
Indicates that the class holds business logic and calls methods in the repository layer.
The @Service annotation is also a specialization of the component annotation.


4)@Controller
-@Controller annotation marks a class as a Spring Web MVC controller and detects @RequestMapping annotations within the class. It too is a
@Component specialization

eg.
@Controller ("employeeController")//employeeController bean name will be registered in DI container
public class EmployeeController
{}

- When you add the @Controller annotation to a class, you can use another annotation i.e. @RequestMapping; to map URLs to instance methods of a class.

5) @Controller Vs @RestController
Spring 4.0 introduced @RestController. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody. The @ResponseBody annotation is active by default.

6) @Valid:  annotation is used for bean validation. @Valid asks spring to validate the associated object. BindingResult contains the outcome of this validation.


Note:
1)Always use these annotations over concrete classes; not over interfaces.
2)In real life, you will face very rare situations where you will need to use @Component annotation. Most of the time, you will using @Repository, @Service and @Controller annotations.



How to enable component scanning
-------------------------------------------------------------------

Above annotation will be scanned and configured only when they are scanned by DI container of spring framework. To enable this scanning, you will need to use “context:component-scan” tag in your spring-servlet.xml file. e.g.

<context:component-scan base-package="com.demo.service" />
<context:component-scan base-package="com.demo.dao" />
<context:component-scan base-package="com.demo.controller" />


Note:When component-scan is declared, you no longer need to declare context:annotation-config, because autowiring is implicitly enabled when component scanning is enabled.


6)@Autowired(required=false) vs @Autowired

The @Autowired annotation can be used with fields or methods for injecting a bean by type

When Spring can’t find a matching bean to wire, it will throw an exception. To fix it, you can disable this checking feature by setting the “required” attribute of @Autowired to false.
Note that only checking feature is disabled not autowiring.
If the Spring can’t find a matching bean, it will leave the property unset.

@Autowired vs new operator
When you use new operator you get a new object every time while spring injects the same singleton object where ever you use @Autowired.
By making scope prototype you are instructing Spring to create new objects for each @Autowired injection.

7)@Qualifier
The @Qualifier annotation us used to control which bean should be autowired on a field.
For example, if we have bean configuration file with two similar beans.

@Component("fooFormatter")
public class FooFormatter implements Formatter {
    public String format() {
        return "foo";
    }
}


@Component("barFormatter")
public class BarFormatter implements Formatter {
    public String format() {
        return "bar";
    }
}


public class FooService {   
    @Autowired
   @Qualifier("fooFormatter")
    private Formatter formatter;

}

By specifying the @Qualifier with the name of the specific implementation, in this case as fooFormatter, we can avoid ambiguity when Spring finds multiple beans of the same type.

@Qualifier annotation matches with the name declared in the @Component annotation.


8) @ModelAttribute
It is used to map your form fields or method return value to  model object and then expose it to a web view.

eg.
    @ModelAttribute
    public void addingCommonObjects(Model model1) {       
        model1.addAttribute("headerMessage", "Techcanvass Solutions-Powai,Hiranandani-Mumbai");
    }

later use this to call in jsp page:
<h1>${headerMessage}</h1>


9)@RequestBody and @ResponseBody annotations are used to bind the HTTP request/response body with object

Aspect Oriented Programming(AOP):
It’s just an interceptor for example Spring AOP can hijack the executing method, and add extra functionality before or after the method execution like logging, caching etc.


Terminologies:
----------------------------------------------------------
1)Join point: a join point always represents a method execution.

2)Advice
Advice represents an action eg. Log4j.

There are different types of advices:
2.1) Before Advice: 
It executes before a join point.
Ex.
@Pointcut("within(com.pkgname.controller..*) 
&& !within(com.indusind.pkgname.DownloadZIPFunction)") 
private void Logging(){}
@Before("Logging()")
public void logBefore(JoinPoint joinPoint) 
{
 log.info("AspectAuditTrail : logBefore : Start");
String methodName=joinPoint.getSignature().getName();
}








2.2) After Returning Advice: 
It executes after a joint point completes normally.
Ex.
@AfterReturning(pointcut = "within(com.pkgname.controller..*) 
&& !within(com.pkgname.controller.DownloadZIPFunction)",
   returning= "result")
 public void logAfter(JoinPoint joinPoint, Object result) 
{
}








2.3) After Throwing Advice: 
It executes if method exits by throwing an exception.


2.4) After (finally) Advice: 
It executes after a join point regardless of join point exit whether normally or exceptional return.

2.5) Around Advice: 

It executes before and after a join point.

Note: there is 3 After Advice


3) Pointcut
 A pointcut defines what advices are required at what join points.
Ex.
@Pointcut("within(com.pkgname.controller..*) 
&& !within(com.pkgname.controller.DownloadZIPFunction)") 
private void Logging(){}

4)Introduction:
An introduction allows you to add new methods or attributes to existing classes.

5)Target Object
It is the object i.e. being advised by one or more aspects. It is also known as proxied object in spring because Spring AOP is implemented using runtime proxies.


Auto scanning tags
1) context:component-scan
2) context:annotation-driven
3) mvc:annotation-config


1) context:component-scan
------------------------------------
context:component-scan eliminates the need for declaring all the beans in the XML files. It will scan the packages for registering the beans to application context.

eg.
    <context:component-scan base-package="org.controller"/>


2) context:annotation-driven
---------------------------------
This will only activate the already registered beans in the context.


3) mvc:annotation-config
---------------------------------
- Enables default mvc configurations.
- If you dont include mvc:annotation-driven your MVC application would work if you have used the context:component-scan



autowiring: (disabled by default)
-If autowiring is enabled then spring container will take care about injecting the dependencies.

- Disadvantage: No control of programmer.


autowire has the following values:
-------------------------------------------
1)byName
2)byType
3)Constructor
4)autoDetect
5)no (default): no autowiring bydefault

1)byName:
------------
-@Autowired
@Qualifier("beanname")

-Property name and bean name must be same ie. It checks whether id in xml file is matching with the property name of java class file.

-If match is not found it  never throws any exception

-It internally calls setter method.















2)byType:
-----------
- Type of property name and bean type should be same.

-So property name and bean name(id) can be different. But there must be only one bean of that type.

-If you have multiple bean of one type, it will not work and throw exception.

eg. below code throws exception
<bean id="a" class="org.sssit.A" autowire="byType"></bean> 
<bean id="b1" class="org.sssit.B"></bean>  //type is of class B
<bean id="b2" class="org.sssit.B"></bean>  // again same type of class B

-It internally calls setter method.















3)Constructor:
-----------------

-Here data type of a bean is same as the data type of constructor argument. It is same as auto wiring "bytype"

-If match is found, it will inject those beans otherwise it will throw exceptions.

-In case of constructor autowiring mode, spring container injects the dependency by highest parameterized constructor.

-If you have 3 constructors in a class, zero-arg, one-arg and two-arg then injection will be performed by calling the two-arg constructor.

- In byType we used setter injection internally here we have to use constructor injection



















4)autoDetect:
----------------

-autowire=”autodetect”
 first will works as Spring Autowiring constructor if not then works as Spring Autowiring byType.



5)no (default):
-----------------
- It is the default autowiring mode. It means no autowiring bydefault.
<bean id="a" class="org.sssit.A" autowire="no"></bean> 



Spring Bean Scope
1) singleton (default)
 Single instance per Spring IoC container (default).

2) prototype
A new instance will be created every time the bean is requested.

3) request
 This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.

4) session
A new bean will be created for each HTTP session by the container.

5) global-session
 global_session scope is equal as session scope on portlet-based web applications.

Syntax:
@Scope("prototype")
public class className {..}


Injecting Prototype Beans into Singleton beans

Using method injection:

public class X {

@Autowired
Y y;

@Lookup
public Y getY() {
return y;
}

public void setY(Y y) {
this.y = y;
}
}

Simply use @Lookup with getY() method, it will return new instance each time.



View Resolvers:
In Spring MVC view resolvers help the Dispatcher Servlet in identifying the views which has to be rendered in response for a request.

Different view resolvers are:
1) XmlViewResolver
2) ResourceBundleViewResolver
3) InternalResourceViewResolver ... and many more


(1)XmlViewResolver:
It accepts a configuration file written in XML.The default configuration file is /WEB-INF/views.xml

(2)InternalResourceViewResolver:
It is the sub class of UrlBasedViewResolver. Spring Tiles uses UrlBasedViewResolver.
It is mapping the simple URLs to the view name. This string will be suffixed and prefixed with suffix and prefix defined in view resolver.

(3)ResourceBundleViewResolver:
If you want to configure your views in the properties files, you can use this resolver.


What is a MultipartResolver and when is it used?
The MultipartResolver interface is used for uploading files.


What is Handler mapping:
It is used to map incoming web requests to appropriate handlers.
When no handler mapping is explicitly specified in configuation, BeanNameUrlHandlerMapping is used by default.

Annotation based handler mapping

@Controller
@Scope("prototype")
public class BranchController
{
@RequestMapping(value = "/addBranch", method = RequestMethod.GET)
public String addBranch()
{
return "addBranch";
}

}


BeanNameUrlHandlerMapping

 <bean     class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>   
   <bean name="/welcome.htm"  class="controller.WelcomeController" />
   <bean name="/streetName.htm"  class="controller.StreetNameController" />
  
Note: There are many "bean name" and "class" under one BeanNameUrlHandlerMapping


  

































Advantages of JdbcTemplate
Less code: By using the JdbcTemplate class, you don't need to create connection,statement,start transaction,commit transaction and close connection, no try catch.

You can execute the query directly.

Different classes:
1.JdbcTemplate
2.SimpleJdbcTemplate
3.NamedParameterJdbcTemplate
4.SimpleJdbcInsert
5.SimpleJdbcCall



How can you fetch records by spring JdbcTemplate?
1.ResultSetExtractor
2.RowMapper


Diff:
-------
1)ResultSetExtractor is suppose to extract the whole ResultSet (possibly multiple rows), multiple row one object
2)RowMapper is feeded with row at a time.The callback will happen once for each row,one row to one object

There is no performance difference



NamedParameter:
In NamedParameter we use names instead of ?(question mark)


Spring MVC Architecture


























Front Controller servlet (DispatherServlet) is responsible for dispatching each request to appropriate handlers, resolving views and finally returning the response.


Spring Batch:
Job:
A job can consist of several steps that execute one after the other. 

Step:
Each step should perform only one defined task.

Tasklet (interface): 
It is used to perform a single task only.
Only one tasklet for step.
Inside tasklet we use chunk.

Chunk:
Chunk allows us to configure how many items you want to read/process/write with the commit-interval property.
Spring Batch commit records according to the commit-interval you defined.

restartable="true"
New JOB instance will not be created.

Ideally, all jobs should be able to start up where they left off.

Configuring Skip Logic:

Errors encountered while processing should not result in Step failure, but should be skipped instead. Once the skip limit is reached, the next exception found will cause the step to fail.
<step id="step1">
   <tasklet>
      <chunk reader="flatFileItemReader" writer="itemWriter"
             commit-interval="10" skip-limit="10">
         <skippable-exception-classes>
            <include class="org.springframework.batch.item.file.FlatFileParseException"/>
         </skippable-exception-classes>
      </chunk>
   </tasklet>
</step>




Good to know concepts of spring:

-Can we have multiple Spring configuration files in one project?
Yes

You can load multiple Java-based configuration files:
@Configuration
@Import({MainConfig.class, SchedulerConfig.class})
public class AppConfig {...}

Or load one XML file that will contain all other configs:
ApplicationContext context = new ClassPathXmlApplicationContext("spring-all.xml");

And inside this XML file you’ll have:
<import resource="main.xml"/>
<import resource="scheduler.xml"/>


How to integrate Spring and Hibernate Frameworks?
Using SessionFactory. SessionFactory provides current session.


What is ContextLoaderListener?
It is used to define spring configurations that will be visible to all other contexts. It’s configured in web.xml file.
eg. log4j.properties, spring-servlet.xml


What is Spring MVC Interceptor and how to use it?
It is used to intercept request and process it.
We can intercept client request at three places – preHandle, postHandle and afterCompletion.
Sometimes we want to intercept the HTTP Request and do some processing before handing it over to the controller handler methods.

HandlerInterceptor vs HandlerInterceptorAdapter:
1)HandlerInterceptorAdapter is an abstract class and HandlerInterceptor is an Interface.
2) So for HandlerInterceptor interface we need to override all three methodspreHandle(), postHandle() and afterCompletion(), whereas for HandlerInterceptorAdapter class we may implement only required methods.
3) It can be used for logging

-What is a Controller in Spring MVC?
All the requests processed by the DispatcherServlet are directed to classes annotated with @Controller. Each controller class maps the requests to methods.


-What is a Spring Bean?
Any normal java class that is initialized by Spring IoC container is called Spring Bean. We use Spring ApplicationContext to get the Spring Bean instance.

Spring IoC container manages the life cycle of Spring Bean, bean scopes and injecting any required dependencies in the bean.

-Bean Life cycle?
1) Creation of bean instance.
2) Set the values to the bean properties.
3) Call the initialization call back method.
4) Bean is ready for use.
5) Call the destruction call back method.


-Name some of the Design Patterns used in the Spring Framework?
Singleton Pattern: Singleton-scoped beans
Prototype Pattern: Prototype-scoped beans
Template Method Pattern: JdbcTemplate, HibernateTemplate, etc.
Model View Controller: Spring MVC
Front Controller: Spring MVC DispatcherServlet
Proxy Pattern: Spring Aspect Oriented Programming support
Adapter Pattern: Spring Web and Spring MVC
Factory Pattern: Bean Factory classes
Data Access Object: Spring DAO support


-How to Get ServletContext and ServletConfig Objects in a Spring Bean?
1)By implementing Spring-aware interfaces(ApplicationContextAware, BeanNameAware etc.).
2)By using @Autowired annotation on those beans:

@Autowired
ServletContext servletContext;

@Autowired
ServletConfig servletConfig;


-How to validate if the bean was initialized using valid values?
Using annotations such as @NotNull, @Min, and @Max.


-What is Spring Security?
Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.
CSRF(Cross site request forgery) attack forces an end user to execute unwanted actions on a web application in which they're currently authenticated.
Example of CSRF attack:
1)CSRFs are typically conducted using email or link that tricks the victim into sending a forged request to a server.
2)unauthorized fund transfers

-How CSRF is enabled in spring security(server side)?(CSRF protection is enabled by default in spring security 4 in pre4 it was disabled) 

In spring-security.xml file
<http>
    ...
    <csrf />
</http>

Also,
Include the CSRF token in our requests on the client side(jsp) as well:
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>

Then we’ll construct the header:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");

$(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
});


-How to call/run a spring batch job
Step1: pass job id in controller
Job job=(Job) applicationContext.getBean("jobIdInXmlFile"); 

Step2: Pass parameter if any
JobParametersBuilder jobParametersBuilder=new JobParametersBuilder();
jobParametersBuilder.addString("fileName",fileName);

Step3: call run method to run a job
JobExecution jobExecution =jobLauncher.run(job, jobParametersBuilder.toJobParameters());

2 comments:

  1. Excellent…Amazing…. I’m satisfied to find so many helpful information here within the put up,for latest php jobs in hyderabad. we want work out extra strategies in this regard, thanks for sharing.

    ReplyDelete