======= Spring Core ======
Why Spring :
1) Light weight Container,
2) Easy to test the code,
3) Loose Coupling,
4) POJO Based Application Development,
5) Supports DI
What is Dependent, Dependency ?
A class is Dependent, its properties/attributes are Dependencies
What is DI ?
It is a Design Pattern which supports Loose Coupling b/w Dependents & Dependencies,
Hollywood principle "Don't call us"(lookup objects),we will call u (inject objects).
What is IOC ?
It is a design Principle of DI, Which manages Object Creation,
Object life cycle management, Destruction, ..etc
Which injection is better (Setter / constructor) ?
Setter inj is preferable, becz we can change the dependency value any no of times,
but with constructor inj we can't change dependency value.
Setter inj makes bean obj as mutable, constructor makes immutable.
With setter inj partial inj dependencies possible, but not with constructor injection
Setter injection Example:
<bean id="e1" class="Emp">
<property name="ename" value="MK"/>
</bean>
Constructor injection Example:
<bean id="e1" class="Emp">
<constructor-arg value="10"/>
</bean>
How to refer bean in parent XML file ?
We have 3 ways to refer reference bean in spring config file
1) bean : refers in the same config file, if not then it refers in parent xml file
2) local : refers in the current container, if not then it refers in parent xml file
3) parent : refers in parent xml file
<bean id="e1" class="Emp">
<property name="ename">
<ref local/bean/parent="p"/>
</property>
</bean>
What is bean alias name ?
Used to define multiple names for a configured spring bean.
<bean id="e1" name="ebean1,ebean2" class="Emp">
<property name="ename" value="MK"/>
</bean>
// also can configure like this for the above bean.
<alias name="e1" alias="ebean3"/>
...
------ Java code to get bean with alias name ----
Emp e=(Emp) factory.getBean("ebean1");
What are bean scopes ?
<bean id="e1" class="Emp" scope="prototype">
<property name="ename" value="Mallikarjun"/>
</bean>
1) singleton : defines only one bean object, this is default, we can use this if
there is no instance variables and static variables to save in the memory. if
with out having static & instance variable if we define class as single ton, if
multiple threads try to access to modify it, then there is a chance of data
inconsistency.
2) prototype : creates spring bean for each time when it is requested
3) request : creates spring bean once per web request, it is applicable only in web
module
4) session : creates the bean once per httpSession, it is applicable only in web
module
5) thread : creates spring bean once per each thread.
What are Spring IOC containers ?
1) BeanFactory (it is light weight container, when we call getBean("") method then
it starts the bean life cycle
2) ApplicationContext (when container starts, it loads spring config file & creates
bean objects)
It supports additional features like JNDI lookup, Transactions, Securities, Logging,
Remoting, EJB Integration, Scheduling, I18N, Event Handling support, ..etc
Spring Bean Life cycle states ?
1) instantiation
2) injecting dependencies
3) initialization
4) Method Ready state
5) destruction
Ex:
public class MyService {
public void init(){
//..
}
public void destroy(){
//..
}
}
<bean id="ms" class="MyService" init-method="init" destroy-method="destroy"/>
(Or) with Annotations with out Spring configuration
public class MyService {
@PostConstruct
public void init(){
//..
}
@PreDestroy
public void destroy(){
//..
}
}
What are Spring Aware interfaces ?
3 types, are
1)BeanNameAware : BeanNameAware is an insteface and it has one method ie.
setBeanName(String), by overriding this method we will get the name of the spring
bean.
2)BeanFactoryAware : BeanFactoryAware is also an interface, is used to get container
info, in which spring bean is available, it has the method
setBeanFactory(BeanFactory).
3)ApplicationContextAware : is also used to get the container information in which
spring bean is available, contains setApplicationContext(ApplicationContext)
method.
What is BeanPostProcessor ? How it is differentiated with bean init(), destroy() methods ?
it is used to define custom logic after the spring contianer finishes instantiating, dependency injection of bean
but bean init(), destroy() methods are specific for one bean.
What is PropertyPlaceConfigurer ?
Some times, spring developers just put the entire deployment details(DB details,
Log file path...etc) in XML config file, but in real time, it is advisable to
place into some external .properties file, becz if property is change just we
need modifications in .properties file instead of XML File.
With this PropertyPlaceConfigurer class configuration, we can configure
the .properties file and also can use the properties dynamically into our spring
config file.
Ex:
----- database.properties -----------
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyongjava
jdbc.username=root
jdbc.password=password
----- spring-config.xml -------------
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>database.properties</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
What is Dependency-check ?
it is used to verify all dependencies of been that are configured via injection are injected or not?
this attributes takes any one of the 4 following values.
1) none (won't check whether dependencies inejcted or not)
2) simple(checks all primitive dependencies inejcted or not)
3) objects(checks all object type dependencies inejcted or not)
4) all(checks all primitives & object type dependencies inejcted or not)
Ex:
<bean id="ms" class="MyService" dependency-check="simple">
</bean>
@Required Annotation :
In Most scenorios, U must need to make sure a paricular property has been set,
but not all properties, For this case we need @Required Annotation.
We need to register an RequiredAnnotationBeanPostProcessor to aware of the
@Required annotation in bean config file.
@Required should use setter methods of bean class.
<beans..>
<context:annotation-config/>
....
<bean class="org.springframeork.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
....
</beans>
Ex:
public clas Car {
private String breaks;
private String driver;
...
@Required
public void setBreaks(String breaks){
this.breaks=breaks;
}
}
What is depends-on attribute of <bean> tag?
For Ex: if A nad B are not directly associated, And still if we want to make sure
that before using Bean A, Bean B Should be created. Then we can go for
"depends-on" attribute.
<bean id="emp" class="Emp" depends-on="mgr,dept"/>
<bean id="mgr" class="Manager"/>
<bean id="dept" class="Department"/>
What is lazy-init attribute of <bean> tag?
ApplicationContext container creates all configured beans, while loading the bean
config files, but some times we don't ant to create the beans until and unless
the rquest comes(call getBean("bean-ref")) for particular bean. This can be
achieved with lazy-init attribute of <bean> tag.
<bean id="e" class="Emp" lazy-init="true">
...
</bean>
How to inject null/empty string values ?
<bean id="e" class="Emp">
<property name="email" vlaue=""/> ===> injecting empty value
<property name="name"><null/></property> ===> injecting null value
</bean>
How to inject inner Beans ?
<bean id="outer" class="OuterClass">
<property name="prop1">
<bean class="Inner">
<property name="name" value="MK"/>
....
</bean>
</property>
</bean>
How to configure Factory Methods :
Ex:
public class SpringBean {
...
public static SpringBean newInstance(){
...//factory method
}
public void businessMethod(){
...//business method
}
}
<bean id="springBeanId" class="SpringBean" factory-method="newInstance">
...
</bean>
invocation :
public static void main(String[] arr){
...
SpringBena springBean=context.getBean("springBeanId",SpringBean.class);
springBean.businessMethod();
...
}
Inheritance :
public class Parent {
private String propertyDocs;
private String bankBalance;
private String deseases;
....
}
public class Child extends Parent {
private String badHabits;
private String knowledge;
....
}
<bean id="child" class="Child">
<property name="proeprtyDocs" value="10 acers land"/>
<property name="bankBalance" value="1000000"/>
<property name="deseases" value="No deseases"/>
<property name="badHabits" value="drinking,smoking"/>
....//can configure both super , sub class properties under Child
</bean>
Injecting Collection objects :
<list> = list of values
Ex :
<property name="srcList">
<list>
<value>1</value>
<value>2</value>
<value>3</value>
</list>
</property>
<set> = set of values with out duplicates
Ex: Same as above use <set> instead of <list>
<map> = collection of name - value pairs
<property name="srcList">
<entry key="111" value-ref="s1"/>
<entry key="112" value-ref="s2"/>
..etc
</property>
<props> = collection of name - value pairs
<property name="srcList">
<props>
<prop key="driverclass">oracle.jdbc.driver.OracleDriver</prop>
....
</props>
</property>
Working with multiple Spring config files :
In two ways we can do this,
1) by importing other spring file into the current config file.
<beans ..>
<import resources="other-spring-config.xml"/>
</beans>
2) by passing all spring bean config files as string array to the constructor of the container
new ClassPathXmlApplicationContext(new String[]{"beans1-confg.xml","beans2-confg.xml","beans3-confg.xml"});
What is p-namespace, c-namespace ?
These are used to limit the amount of XML you have to write, to configure your
beans, instead of using <property/> elements we can use p-namespace to configure
properties of bean, and c-namespace is used to configure constructor args of bean
instead of using <constructor-arg> elements.
Ex1 on Property Config :
<bean id="address" class="Address" p:city="Hyd" p:hno="2-1-22"></bean>
Ex2 on Constructor Config:
public class Address {
private String city;
private String hno;
@ConstructorProperties({"cityName","houseNumber"})
public Address(String city,String hno){
this.city=city;
this.hno=hno;
}
.....
}
<bean id="address" class="Address" c:cityName="Hyderabad" c:houseNumber="15-2A"/>
Spring I18N :
Step-1) Define properties Files
1) ApplicationResources_en_US_SiliconValley.properties
Some message here (key -value pairs)
2) ApplicationResources_fr_CA.properties
Some message here (key -value pairs)
3) ApplicationResources_zh_CN.properties
Some message here (key -value pairs)
Step-2) Configure the properties files in configuration file
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="ApplicationResources"/>
</bean>
Step-3) write client programe
String message=context.getMessage("messasge from PropFile", new Object[]{"US","English"},new Locale("en","US",SiliconValley"));
S.o.pl(message);
String message=context.getMessage("messasge from PropFile", null ,new
Locale("zh","CN"));
S.o.pl(message);
...etc
Spring Event Handling :
Usefull to handle events for ApplicationListener events, like container started or stopped ..etc
All these events are monitored by ApplicationListener which is implemented by ApplicationContext container.
Built-in events are :
1) ContextRefreshedEvent : raised when the ApplicationContext is either initialized or refreshed.
2) ContextStartedEvent : when the ApplicationContext is started using the start() method
3) ContextStoppedEvent : when the ApplicationContext is stopped using the stop() method
4) ContextClosedEvent: when the ApplicatonContext is closed using the close() method
AutoWiring :
The Spring container can autowirre relationships b/w collabaorating beans with out
suing <constructor-arg> and <property> elements which helps cut down on the
amount of XML configuration
Autowiring means automatically injecting the dependencies
instead of maually configuring the injecting we done it automatically by using
auto wiring.
There are 5 possible valus to the autowire attribute of <bean> tag.
1) no : It won't allow autowiring
2) constructor : it checks he constructore parameter types in that bean, then
checks is thre any bean configured with same type in spring configuration file,
if finds it will be injected, if no simply it ignores.
<bean id="employeeService" class="EmployeeService" autowire="byConstructor"/>
(Or)
public class Customer {
...
@Autowired
public Customer(Person p){
....
}
}
3) byName :autoWire="byName", it checks all setter methods in that bean, and for
each setter method it will check is there any corresponding bean is configured
in psring config file, if finds it wil be injecte, if not simply it ignores.
Ex:
if there is a setter method setEmp(Employee emp) then container checks for a bean
whose id id "emp". if finds then, it will inject hat bean using
"setEmp(Employee e)" method. if not found any bean with id "emp" then it simply
ignores.
<bean id="employeeService" class="EmployeeService" autowire="byName"/>
4) byType : autoWire="byType" for any bean in the configuration, then it checks
all setter methods(having only one parameter in that bean. And for each setter
method it will check parameter type, then checks is there any bean configured
with same type in spring configuration fle, If finds it will be injected, if not
simply it ignores.
Ex:
if there is a setter method "setSomeThing(Employee eployee)" then container
checks for bean whose type is "Employee". If it finds then, it will inject that
bean using the method.
<bean id="employeeService" class="EmployeeService" autowire="byType"/>
5) autoDetect :
@Qualifier :
is used to control which ban should be autowire on a field, for Example, bean
configuration file with two similar person Beans
Ex:
<bean id="customer" class="Customer">
..
</bean>
<bean id="personBean1" class="Person">
..
</bean>
<bean id="personBean2" class="Person">
..
</bean>
public class Customer {
@Autowired
@Qualifier("personBean1")
private Person person;
.....
}
Spring Auto Scanning Components :
With AutoScan spring automatically scan, detect and instantiate your beans from
pre-defined project package
@Component is annotation indicates to the class is a autoscan component exists in
the base configured package in the config file, So it scan the package if exists
it automaticall creates bean object
@Component
pulic class CustomerDAO{
...
}
<beans ...>
<context:component-scan base-package="com.mk.dao"/>
....
</beans>
there are 4 types of auto components scan annotation types
1) @Component = indicates a auto scan components
2) @Repository = indicates DAO component in the persistance layer
3) @Service = indicates a service component in the business layer
4) @Controller = indicates a controller component in the presentation layer.
Spring Filter Component in Auto Scanning :
1) filter component - include
Ex:
<beans ...>
<context:component-scan base-package="com.mk.dao">
<context:include-filter type="regex" expression="com.mk.dao.*DAO.*"/>
<context:include-filter type="regex" expression="com.mk.service.*Service.*"/>
</context:component-scan>
</beans>
2) filter component - exclude
============== Spring MVC =============
Spring MVC Flow :
1) Request ->Dispatcher Servlet(Front Controller) ->handlerMapper
(Used to identify the particular controller for the given ID)
2) the HandlerMapper identifies the particular controller and gives to
DispatcherServlet
3) DS calls handleRequest(req,Res) methods on Controller, this controler class
write with @Controller, @RequestMapping annotations
4) Then the controller after completion of request hanlder method call, it returns
ModelAndView object(which consist view name) back to the DS.
5) Then DS, tries to get the actual view by consulting the ViewResolver Object by
passing View Name
6) The ViewResolver selects view is rendered back to the DS.
7) DS consult the particular View with the Model
8) View executes and returns HTML o/p to the DS.
9) Then DS sends the o/p to browser.
Purpose of InternalResourceView in Bean config file
Used to map the logical name of the Resource as returned by the controller object
to the physical view location(WEB-INF/jsp/result.jsp)
What is component-scan in Spring MVC ?
<context:component-scan base-package="package.name" />
=> It tells to the Spring container to auto scan the entire package to identify
the controller components. Basically this scan is not only for identifying the
controller components, all the configurations are scanned and used by the
container. If you are not specifying the package, spring will not scan your
components and your application may not work.
Spring MVC Annotations Purpose:
1) @Controller:
This annotation is used at the class level.
Denotes that the marked class acts as a controller.
2) @RequestMapping:
This annotation can be used at the class level and method level.
This annotation accepts the following as its parameters.Please note that all
the arguments are optional.
String[] values – Represents an array of URLs which tells that the controller
should be invoked for the request which arrive with the list of URLs mentioned.
Eg: @RequestMapping(value={"/welcome", "/test"}.
RequestMethod[] methods – An array of HTTP methods. This is optional parameter
and when not mentioned, the default method is HTTP GET. If specifically mentioned
like POST, TRACE etc., then the method or controller will be invoked only when the
request comes with the mentioned method.
Eg: @RequestMapping(method=RequestMethod.GET).
String[] Params – An array of Request Parameters and their values which can be
used to validate if a particular request parameter has a value.
Eg. @RequestMapping(params="myParam=myValue")
String[] headers - An array of headers which can be used to validate the values
that the headers carry in request object. This is used for validation purposes
same as the Params[] discussed earlier.
Eg.@RequestMapping(headers = "content-type=text/*")
3) @Sessionattributes is used for passing the values across the different pages
through the session.
Annotation Use Description
@Controller Type Stereotypes a component as a Spring MVC
controller.
@InitBinder Method Annotates a method that customizes data
binding.
@ModelAttribute Parameter, Method When applied to a method, used to preload
the model with the value returned from the
method. When applied to a parameter, binds
a model attribute to the parameter. table
@RequestMapping Method, Type Maps a URL pattern and/or HTTP method to a
method or controller type.
@RequestParam Parameter Binds a request parameter to a method
parameter.
@SessionAttributes Type Specifies that a model attribute should be
stored in the session.
Spring MVC Form Validations :
Step-1) Add Beanvalidation, HibernateValidation dependencies into pom.xml
Step-2) Define model class with validator annotations
Ex:
public class User {
@NotEmpty
@Email
private String email;
@NotEmpty(message = "Please enter your password.")
@Size(min = 6, max = 15, message = "Your password must between 6 and 15 characters"
private String password;
public String getEmail() {
return email;
}
}
Step-3) Define JSP form with error messages
Ex:
<form:form action="login" commandName="userForm">
<tr>
<td align="left" width="20%">Email: </td>
<td align="left" width="40%"><form:input path="email" size="30"/></td>
<td align="left"><form:errors path="email" cssClass="error"/></td>
</tr>
<tr>
<td>Password: </td>
<td><form:password path="password" size="30"/></td>
<td><form:errors path="password" cssClass="error"/></td>
</tr>
<tr>
<td></td>
<td align="center"><input type="submit" value="Login"/></td>
<td></td>
</tr>
</form:form>
Step-4) Define Controller with request handler method to ensure errors in the form
Ex:
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(@Valid @ModelAttribute("userForm") User userForm,
BindingResult result, Map<String, Object> model) {
if (result.hasErrors()) {
return "LoginForm";
}
return "LoginSuccess";
}
Spring MVC Tiles :
Step-1) Configure the following two classes in spring config files
a) org.springframework.web.servlet.view.tiles2.TilesView
b) <bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
Step-3) Define tiles.xml in WEB-INF folder
<tiles-definitions>
<definition name="base.definition" template="/WEB-INF/jsp/layout.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/WEB-INF/jsp/header.jsp" />
<put-attribute name="menu" value="/WEB-INF/jsp/menu.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/jsp/footer.jsp" />
</definition>
<definition name="contact" extends="base.definition">
<put-attribute name="title" value="Contact Manager" />
<put-attribute name="body" value="/WEB-INF/jsp/contact.jsp" />
</definition>
</tiles-definitions>
Step-3) Define JSP's in Relevant folder (WEB-INF/jsp)
Struts-Spring Integration :
Step-1) Define Struts-config.xml with DelegatingRequestProcessor,
ContextLoaderPlugin for spring-config.xml file
Step-2) Define beans in spring-config.xml, which need to inject into struts action
class (like service classes, dao classes,..etc)
Reaming is same ...