Class Notes
Class Notes
Class Notes
-------------------------
Softwares Required
------------------
1) Maven
2) IDE
3) JDK 8 or higher
4) Spring jars
5) Commons-Logging jar
1)BeanFactory
2)ApplicationContext
ClassPathResource
FileSystemResource
String fileName="Beans.xml";
Resource resource = new ClassPathResource(fileName);
BeanFactory factory = new XmlBeanFactory(resource);
----------------------------------------------------------------
If xml follows above 2 rules then we can say that xml is well-formed. If xml is
wellformed humans & machines can read that xml.
<person>
<id>101</id>
<name>Raju</name>
<adress>
<city>Hyd</city>
<state>TG</state>
</adress>
</person>
--------------------------------------------------------------
<order>
<item>
<code>101</code>
<quantity>abc</quantity>
</item>
<address>
<city>Hyd</city>
<state>TG</state>
<zip>500081</zip>
</address>
</order>
======================================================================
Xml
---
1) Simple Element
<id>101</id>
2) Compound Element
<name>
<first-name>Cedrone</first-name>
<last-name>Charles</last-name>
</name>
-----------------------------------------------------------------
--------JAX-P API-------------------
SAX
DOM
STAX
----------------------------------------------
------------------------Beans.xml------------------------
<beans>
</beans>
----------------------------------------------------------
ClassPathResource
FileSystemResource
------------------------------------------------------------------
1) BeanFactory
Resource resource =
new ClassPathResource("com/maruti/cfg/Beans.xml);
BeanFactory factory =
new XmlBeanFactory(resource);
---------------------------------------------------------------------
4) BeanFactory will load all beans defintions from xml file and
will store BeansMetaData (in memory).
----------------------------------------------------------------------
factory.getBean("car");
Object obj = factory.getBean("paymentCtx");
PaymentContext ctxt = (PaymentContext) obj;
-------------------------------------------------------------
PaymentContext ctxt = (PaymentContext) factory.getBean("paymentCtx");
-------------------------------------------------------------------PaymentContext
ctxt =
factory.getBean("paymentCtx",PaymentContext.class);
--------------------------------------------------------------------
Constructor Injection:
----------------------
INjecting dependent class object into target class by calling
target class constructor is called as Constructor Injection(CI).
------------------------------------------------------------------
<bean id="car" class="pkg.Car">
<constructor-arg name="eng" ref="petrolEng" />
</bean>
----------------------------------------------------------------
setter method : setter injection
class Person {
}
----------------------------------------------
<bean id="person" class="pkg.Person">
<property name="personId" value="101" />
<property name="personName" value="John"/>
<property name="personAge" value="25"/>
</bean>
PaymentContext(IPayment payment){
System.out.println(p); //com.hps.beans.Person@2ed94a8b
System.out.println(p.toString());com.hps.beans.Person@2ed94a8b
-================================================
public String toString(){
return
this.getClass().getName()+"@"+Integer.toHexString(this.hashCode());
com.hps.Person@e979l96
------------------------------------------------------------------------
Collection Injection
--------------------
List
Set
Map and
Properties
<property name="places">
<list>
<value>Hyd</value>
<value>Pune</value>
</list>
</property>
-------------------------------------------------------
private Set<Long> phnos; //java.util.LinkedHashSet
<property name="phnos">
<set>
<value>0808080</value>
<value>9797979</value>
</set>
</property>
--------------------------------------------------------
private Map<String,Long> projectCodes; //java.util.LinkedHashMap
<property name="projectCodes">
<map key-type="" value-type="">
<entry key="" value="" />
<entry key="" value""/>
</map>
</property>
---------------------------------------------------------------------
<property name="emails">
<props>
<prop key="personal">iyiy</prop>
<prop key="ofc"></prop>
</props>
</property>
------------------------------------------------------------------
Enumeration
Iterator
ListIterator
SplitIterator (jdk 1.8)
Movie.java
----------
Note: In Constructor Injection, its mandatory that we need to inject values for all
the variables.
If we don't know value for a variable, then we shuld use null injection.
<constructor-arg name="movieName">
<null />
</constructor-arg>
Bean Scopes
-----------
Bean Scope will decide how many objects should be created for a bean class in IOC
container.
syntax :
-------
<bean id="car"
class="pkg.Car"
scope="singleton|prototype|request|session" />
factory.getBean("movie",Movie.class); //
singleton
prototype
request
session
BeanFactory
-----------
It is an interface
It is used to start IOC Container
IT is Lazy Container
Why it is called as Lazy ? :: Until unless we call getBean( ) method bean object
will not be created.
how many objects should be created for a bean depends on bean scope.
ApplicationContext
------------------
It is an interface
It is also used to Start IOC Container
It is Eager container
Why it is Eager Container ? :: When IOC starts immediatley it will create bean
objects if scope is singleton and lazy-init=false.
It supports I18N
It supports Event Handling
It supports Web Application Development
ApplicationContext ctx =
new ClasspathXmlApplicationContext(String filePath)
Bean Inheritence
----------------
What is Inheritence?
--------------------
Bean Inheritence
----------------
To copy properties from one bean to another bean we can use Bean Inheritence
concept in Spring.
Note: If property is not declared in child bean definition then only IOC will copy
parent bean property value to child bean property.
public class Car {
int id;
String name;
Double price;
String color;
String regNum;
//setters
//toString()
}
-----------------------------------------------------------------------
<bean id="c1" class="pkg.Car">
<property name="id" value="101"/>
<property name="name" value="Swift" />
<property name="price" value="850000"/>
<property name="color" value="Red"/>
<property name="regNum" value="TG 27 ES 6868"/>
</bean>
Collection Merging
------------------
If we want to copy collection properties from one bean to another bean then we can
use Collection Merging.
-----------------------------------------------------------------------
Meeting :
id = 101
name = Triage Meeting
purpose = To discuss defects occured in UAT
participants = john, Ram, Sita, Gita
Scrum Meetings
Status Meetings
Triage Meetings
Manual Wiring
------------
Injecting dependent object into target object using ref attribute.
AutoWiring
----------
IOC can identify dependent object and it can inject into target object.
byName:
-------
With target class user-defined variable name there should be a bean in bean
configuration file. Then that bean will be considered as dependent bean and it will
be injected to target bean.
If we don't have any bean defintion which is matching with target class user
defined type variable then autowiring can't be performed.
Note : IOC will check varibale name with bean id or bean name.
byType:
-------
IOC will check user-defined varible data type with bean class in bean configuration
file. If variable data type and Bean class is same then ioc consider that bean as
dependent bean and it will inject that bean to target.
Note : There is a possibility that one class can be configured with multiple bean
definitions using unique ids. In this sitatuion IOC can't identify dependent bean
hence it will throw Exception (NoUniqueBeanDefinitionFound).
To resolve this we can use 'primary' attribute in bean defition. The bean which
contains primary=true is called as auto-wire candidate.
byName - variable name should match with bean name
constructor
constructor
-----------
What is Spring
Spring Advantages
Spring Modules
IOC
Dependency Injection
Setter Injection
Constructor Injection
Setter Injections vs Constructor Injection
BeanFactory
ApplicationContext
Injecting Inner Beans
Collection Injection
Bean Scopes
Bean Inheritence
Collection Merging
Autowiring
P & C namespaces
Bean Aliasing
Depends On
Aware Interfaces
Static Factory Method Instantiation
Instance Factory Method Instantiation
Nested Bean Factory
Multiple Configuration Files
Method Injections (Lookup method & Method Replacment)
Bean Life Cycle
Bean Post Processor
Bean Factory Post Processor
----------------------------------------------------------------------
----------------------------------------------
IOC
DI ( SI & CI )
<bean id=""
class=""
scope=""
parent=""
abstract=""
lazy-init=""
autowire="" >
<property />
<constructor-arg />
</bean>
<bean id=""
class=""
scope=""
parent=""
abstract=""
lazy-init=""
autowire="" >
</bean>
-----------------------------------------
class Contact {
int contactId;
String contactName;
Long contactNumber;
Address addr;
//Setter methods
//toString( )
}
----------------old approach---------------------------
<beans <xsd linking> >
<bean id="c" class="pkg.Contact">
<property name="contactId" value="101" />
<property name="contactName" value="Raj"/>
<property name="contactNumber" value="797979979"/>
<property name="addr" ref="a"/>
</bean>
</beans>
---------------------using p-namespace-----------
<beans xsd-linking p-namespace-url >
Depends-On
----------
class Car {
class Robot {
private Chip chip;
}
-------------------------------------------------------------
<bean id="c" class="pkg.Chip" />
Bean Aliasing
=============
Note : When we configure multiple names for a bean using name attribute space and
comma will be considered as delimter.
If you want write a bean name including comma or space then we should use alias
tag.
------------------------------------------------------------------
Amazon - E-Commerce
BlueDart
Bean Life Cycle
---------------
To perform initialization and destruction operations for a Bean we can use bean
life cycle.
- IntializingBean- afterPropertiesSet()
- DisposableBean- destroy()
3) Annotation approach
<bean id="e1" class="pkg.Engine" />
------------------------------------------------
p2
p3
p4
p5,
id vs name
ApplicationContext
------------------
Aware Interfaces
------------------
This concept is also called as Interface Injection.
BeanFactoryAware
----------------
//logic
}
Factory Methods
---------------
The method which is responsible to creat same or different class object is called
as factory method.
Calendar c = Calendar.getInstance();
char ch = msg.charAt(0);
class Car {
-------------------------------------------
12-May-2019 + 57 = ?
new Date()
SimpleDateFormat
----------------
Date parse(String str) -----> String to Date conversion
----------------------------------
I 18 N
Property Editors
Event Handling
Spring Core Annotations
web components
service components
persistent components
Method Injections
-----------------
1) LookUp method Injection : When we want to inject prototype bean into singleton
bean
tg.getToken(); // 1234
tg.getToken( ); //1234
Car c1 = ctxt.getBean("c",Car.class);
sysout(c1.getClass().getName()); //pkg.Car
sysout(tg.getClass().getName()); //pkg.TokenGenerator$Proxy
In this situation our project classes are tightly coupled with spring framework
dependencies.
-> To execute post initialization and pre-destruction logic we can write in user
defined methods.
Bean Post Processor will execute after bean instantiation and before bean
initialization.
3) Annotation approach
------------------------
BeanPostProcessor
------------------
This is used to execute some common logic for all beans before initialization and
after initialization.
BeanFactoryPostProcessor
------------------------
This is used to modify ioc container metadata.
FactoryPostProcessor will execute after beans are loaded and before instantiation
of beans.
one is PropertyPlaceholderConfigurer
PropertyPlaceholderConfigurer
Property Editors
----------------
Integer id;
String name;
Double ticketPrice;
//setter methods
}
<bean id="m" class="pkg.Movie">
<property name="id" value="101"/>-- setId(101);
<property name="name" value="Titanic"/> -- setName("Titanic")
<property name="ticketPrice" value="350.00"/>
--setTicketPrice(350.00);
</bean>
PropertyEditors
-----------------
languageCode_CountryCode
hi_IN
-----------------------------------------------------------------
Resource Bundles
key=value
------baseName.properties----------------
key=value
--------baseName_langCd_CountryCode.properties----------
---------------------------------------------------------------
ctxt.getMessage(key,new Object[]{"Raju"},Locale.GERMANY);
Property Editors
----------------
setNums(10,20) ; //in-valid
----------------------------------------------------------------------