ewewessssswwwsssssssssdia" />
Depends-On
----------
class Car {
private Engine eng;
class Robot {
private Chip chip;
}
-------------------------------------------------------------
<bean id="c" class="pkg.Chip" />
<bean id="r" class="pkg.Robot">
<property name="chip" ref="c"/>
</bean>
-------------------------------------------------
<bean id="emiCalc" class="pkg.EmiCalculator"
depends-on="cacheManager"/>
Bean Aliasing
=============
<bean name="c1,c2 c3" class="com.maruthi.Car" />
=========================================
Car c1 = ctxt.getBean("c1",Car.class);
Q)what is the difference between id and name attributes in bean tag?
Using id we can configure only one value
Using name we can configure more than one name
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.
<alias name="res1" alias="res5," />
------------------------------------------------------------------
Amazon - E-Commerce
BlueDart
Bean Life Cycle
---------------
To perform initialization and destruction operations for a Bean we can use bean
life cycle.
Like init operation and destroy operation.
Bean life cycle we can achieve in below 3 ways
----------------------------------------------
1) Programmatic approach
- we need to implement 2 predefined interfaces of spring
- IntializingBean- afterPropertiesSet()
- DisposableBean- destroy()
2) Declarative approach (xml)
3) Annotation approach
<bean id="e1" class="pkg.Engine" />
<bean id="car1" class="pkg.Car">
<property name="eng" ref="e1"/>
</bean>
<bean id="car2" class="pkg.Car">
<property name="eng" ref="e1"/>
</bean>
---------------------------
ctxt.getBean("e1",Engine.class); // valid
ctxt.getBean("car",Car.class); // valid
------------------------------------------------
<bean id="c" class="pkg.Car">
<property name="eng">
<bean class="pkg.Engine" id="eng" />
</property>
</besassssan>
--------------------------------
ctxt.getBean("eng",Engine.class); //invalid
ctxt.getBean("car",Car.class); // valid
id and name attributes in bean tag.
<bean id="p1" class="" />
<bean name="p1,p2,p3 p4" class="" />
<alias name="p1" alias="p5," />
------------------------------------------
String[] names = ctxt.getAliases("p1");
p2
p3
p4
p5,
Amazon ---- > BlueDart ---- For cities delivery
Amazon ----> DTDC ----- For Villages delivery
if(zip>=500080) ---- City --- BlueDart obj
if(zip < 500080 ) --- village ---- Dtdc obj
amazon -- bluedart -- cities
amazon -- dtdc -- villages
Bean Aliasing
-------------
id vs name
<bean id="car" class="" />
<bean name="c1,c2,c3 c4" class="" />
<alias name="c1" alias="c5," />
ApplicationContext
------------------
Alias tag in config file
Aware Interfaces
------------------
This concept is also called as Interface Injection.
Dependency Injection is performing through interface hence it is called as
Intessssssssssssssssssssssssssssssrface iNjection.
Ex : BeanFactoryAware and ApplicationContextAware etc...
If we don't know which dependent object should be injected into target at
compilation time then we can inject IOC to our target.
If IOC is injected to our target class, then target class can decide which
dependent object it should load in runtime based on conditions.
BeanFactoryAware
----------------
class AmazonService implements BeanFactoryAware {
private BeanFactory factory = null;
public setBeanFactory(BeanFactory factory){
this.factory = factory;
}
//logic
}
Factory Methods
---------------
The method which is responsible to creat same or different class object is called
as factory method.
Factory methods can be classified into 2 types
1) Static factory method
Connection con = DriverManager.getConnection(url,uname,pwd);
Calendar c = Calendar.getInstance();
2) Instance Factory Method
String msg = "hello";
String sub = msg.substr(0,3);
char ch = msg.charAt(0);
class Car {
<bean id="c" class="pkg.Car" />
--------------------------------------------
<bean id="al" class="java.util.ArrayList" />
-------------------------------------------
<bean id="calc" class="java.util.Calendar"
factory-method="getInstance" />
Calendar c = Calendar.getInstance( ) ;
================Static Factory method Instantiation================
<bean id="cal"
class="java.util.Calendar"
factory-method="getInstance" />
===================================================================
12-May-2019 + 57 = ?
addDays(Date d, int days) {
cal.setTime(d);
cal.add(Calendar.DAY,days);
Date finalDate = cal.getTime();
}
new Date()
String str = "10-May-2019" ;
SimpleDateFormat
----------------
Date parse(String str) -----> String to Date conversion
String format(Date d) ------> Date to String Conversion
Instance Factory Method Instantiation
=====================================
----------------------------------
I 18 N
Property Editors
Event Handling
Spring Core Annotations
Mutitple Configuration Fies
---------------------------
web components
service components
persistent components
Method Injections
-----------------
1) LookUp method Injection : When we want to inject prototype bean into singleton
bean
2) Method Replacement : If we want to replace one method with another method in
runtime.
<bean id="t" class="pkg.Token" scope="prototype" />
<bean id="tokenGenerator" class="pkg.TokenGenerator">
<property name="token" ref="t"/>
</bean>
----------------------------------------------------------------
TokenGenerator tg =
ctxt.getBean("tokenGenerator",TokenGenerator.class);
tg.getToken(); // 1234
tg.getToken( ); //1234
<bean id="t" class="com.airtel.beans.Token" scope="prototype" />
<bean id="tg" class="com.airtel.beans.TokenGenerator">
<property name="token" ref="t" />
</bean>
==========================================================
<bean id="t" class="com.airtel.beans.Token" scope="prototype" />
<bean id="tg" class="com.airtel.beans.TokenGenerator">
<lookumethod name="generateToken" />
</bean>
public abstract class TokenGenerator {
public abstract Token generateToken();
}
----------------------------------------------------
public class TokenGenerator$Proxy extends TokenGenerator{
public Token generateToken(){
return new Token();
}
}
---------------------------------------------------------
<bean id="c" class="pkg.Car" />
Car c1 = ctxt.getBean("c",Car.class);
sysout(c1.getClass().getName()); //pkg.Car
<bean id="tg" class="pkg.TokenGenerator">
</bean>
TokenGenerator tg = ctxt.getBean("tg", TokenGenerator.class);
sysout(tg.getClass().getName()); //pkg.TokenGenerator
=============================================================
<bean id="t" class="pkg.Token" />
<bean id="tg" class="pkg.TokenGenerator">
<lookup-method name="generateToken" />
</bean>
TokenGenerator tg = ctxt.getBean("tg", TokenGenerator.class);
sysout(tg.getClass().getName()); //pkg.TokenGenerator$Proxy
Bean Life Cycle
---------------
To perform some operation for a bean post initialization and
pre-destruction then we can use Bean Life Cycle.
Post Initialization : object Creation and initialing values to obj
Pre Destruction : Before removing object from IOC.
In below 3 ways we can achieve bean life cycle
===============================================
1) Programmatic approach
- We need to implement 2 interfaces
- InitializingBean -> afterPropertiesSet( )
- DisposableBean -> destroy( )
In this approach our bean class is implementing 2 predefined spring interfaces
hence we are loosing non-invasiveness of our project.
In this situation our project classes are tightly coupled with spring framework
dependencies.
To avoid this problem, we can go for Declarative appoach
2) Declarative approach - xml approach
---------------------------------------
- > In this approach we no need to implement any interfaces.
-> To execute post initialization and pre-destruction logic we can write in user
defined methods.
m1() - after properties set logic
m2() - pre destruction logic
<bean id="motor" class="pkg.Motor"
init-method="m1"
destroy-method="m2" />
Bean Life Cycle is applicable for only one bean.
Bean Post Processor is appliable for all beans in IOC.
Bean Post Processor will execute after bean instantiation and before bean
initialization.
Note 1: ApplicationContext can recognize BeanPostProcessor automatically and will
register those.
Note 2: BeanFactory can't recognize BeanPostProcessor automatically so we need to
register BeanPostProcessor with BeanFactory.
3) Annotation approach
------------------------
--> First ioc will create object
--> IOC will inject dependencies if any presented
--> IOC will call afterPropertiesSet( ) method
BeanPostProcessor
------------------
This is used to execute some common logic for all beans before initialization and
after initialization.
BeanFactory can't recognize BeanPostProcessor automatically where as
ApplicationCOntext can recognize BeanPostProcessors.
BeanFactoryPostProcessor
------------------------
This is used to modify ioc container metadata.
FactoryPostProcessor will execute after beans are loaded and before instantiation
of beans.
<bean id="cm" class="pkg.ConnectionManager">
<property name="url" value="${url}" />
<property name="uname" value="${uname}" />
<property name="pwd" value="${pwd}" />
<property name="driverCls" value="${driverCls}" />
</bean>
-------------------------------------------------------
we have so many predefind BeanFactoryPostProcessor classes in spring
one is PropertyPlaceholderConfigurer
BeanFactoryPostProcessor :- After Beans are loaded and before Instantiation BFP
will execute.
PropertyPlaceholderConfigurer
Ex : loading values from Properties file.
BeanPostProcessor:- AFter Bean Instantiation and before Initialization
BPP will execute.
Bean Life Cycle : After Initialization and Before Destruction .
Internationalization (I 18 N)
----------------------------
Locale : It represents one geographic location.
Locale l = Locale.getDefaultLocale(); // US_EN
US - country code
EN - language code
Property Editors
----------------
public class Movie {
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
-----------------
Locale : One Geographic location
languageCode_CountryCode
Locale l = new Locale("hi","IN"); // hindi locale
hi_IN
-----------------------------------------------------------------
Resource Bundles
key=value
------baseName.properties----------------
key=value
--------baseName_langCd_CountryCode.properties----------
<bean id="messageSource" class="pkg.ResourceBundleMessageSource">
<property name="baseName" value="messages"/>
</bean>
---------------------------------------------------------------
ctxt.getMessage(key,new Object[]{"Raju"},Locale.GERMANY);
Property Editors
----------------
Property Editors are used to convert values to corresponding data types.
private Integer age; // setAge(Integer age)
<property name="age" value="50" /> --- NumberPropertyEditor
private Double price; // setPrice(Double price)
<property name="price" value="500.89" /> - DecimalPropertyEditor
public void setNums(Numbers nums){
//logic
}
setNums(new Numbers()); // valid
setNums(10,20) ; //in-valid
----------------------------------------------------------------------