Dependency Injection     rgupta.trainer@gmail.com
Dependency Injection•  Hello World DI•  Using setter, Constructor Injection•  Injecting Objects•  Inner Beans, Aliases•  I...
Introduction to DI    rgupta.trainer@gmail.com
interfaceDesign as per interface                          rgupta.trainer@gmail.com
Car depends on Wheel                       rgupta.trainer@gmail.com
Most important :glue it all with XML                       rgupta.trainer@gmail.com
DI ?• DI is how objects or bean using Spring are brought together by container  to accomplished the task• It is AKA of IoC...
How Spring Work?    rgupta.trainer@gmail.com
• Any object outside  container get bean by  providing ref• We know object requiring  bean contact to container ie  Applic...
Spring Hello world example         rgupta.trainer@gmail.com
rgupta.trainer@gmail.com
Setter injection….Ex      rgupta.trainer@gmail.com
Injecting Objects    rgupta.trainer@gmail.com
rgupta.trainer@gmail.com
Inner Beans• Remove the definition of  Point bean and put into  triangle bean• Remove the ref tag and put  definition insi...
Aliases• alias giving name  to same bean• Use alias tag• Now bean can be  referred by new  name                      rgupt...
Spring bean scopes• In Spring, bean scope is used to decide which  type of bean instance should be return from  Spring con...
Bean Scopes           Scope                                    Description          Singleton          (Default)Only one s...
Singleton scopectx.getBean(“student”)                            Spring                           Container               ...
Output in case ofdefault bean scope                     rgupta.trainer@gmail.com
Prototype scopectx.getBean(“student”)                            Spring                           Container               ...
rgupta.trainer@gmail.com
Spring Collection• What if member variable is collection  major collection types are supported in  Spring  List – <list/> ...
Injecting list..rgupta.trainer@gmail.com
rgupta.trainer@gmail.com
Auto Wiring• Skip some of the configuration that we have  to do by intelligent guessing what ref is• AKA shortcut.• Type o...
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.o...
Aware interfaces..• BeanName Aware interface     • Want to know the name of bean configured• ApplicationContextAware     •...
Bean Definition Inheritance• Lets say we have 100 bean definition in xml ,  lets we have common definition in each bean  d...
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.o...
Lifecycle Callbacks• Spring provide us call-back method for life cycle  of bean           • for initialization of bean    ...
cofig init and destroyed method• Choice I            • implements InitializingBean,DisposableBean• Choice II            • ...
public class Tringle implements                                              public void setPointC(Point pointC) {      In...
Method Injection – Method Replace          class MobileStore{                   public String buyMobile(){                ...
Lookup Method Injectionpublic abstract class BookStore {                     public interface Book {                      ...
Thanks !!! rgupta.trainer@gmail.com
Upcoming SlideShare
Loading in …5
×

Spring 3.0 dependancy injection

870 views

Published on

Spring 3.0 dependancy injection examples

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
870
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Spring 3.0 dependancy injection

  1. 1. Dependency Injection rgupta.trainer@gmail.com
  2. 2. Dependency Injection• Hello World DI• Using setter, Constructor Injection• Injecting Objects• Inner Beans, Aliases• Initializing Collections• Understanding Bean Scopes• Bean Autowiring• Using ApplicationContextAware• Bean Definition Inheritance• Lifecycle Callbacks• Method injections• Lookup method injection• …• … rgupta.trainer@gmail.com
  3. 3. Introduction to DI rgupta.trainer@gmail.com
  4. 4. interfaceDesign as per interface rgupta.trainer@gmail.com
  5. 5. Car depends on Wheel rgupta.trainer@gmail.com
  6. 6. Most important :glue it all with XML rgupta.trainer@gmail.com
  7. 7. DI ?• DI is how objects or bean using Spring are brought together by container to accomplished the task• It is AKA of IoC• In most application and object is responsible for its own dependencies or associated objects and this is mostly achieved using JNDI• In DI approach we allow container to manages dependencies of object creation and associationHollywood ; don’t call me I will call you rgupta.trainer@gmail.com
  8. 8. How Spring Work? rgupta.trainer@gmail.com
  9. 9. • Any object outside container get bean by providing ref• We know object requiring bean contact to container ie Application context that refer SpringXML and create a Spring managed bean and that can be referred by requesting object outside/inside the container rgupta.trainer@gmail.com
  10. 10. Spring Hello world example rgupta.trainer@gmail.com
  11. 11. rgupta.trainer@gmail.com
  12. 12. Setter injection….Ex rgupta.trainer@gmail.com
  13. 13. Injecting Objects rgupta.trainer@gmail.com
  14. 14. rgupta.trainer@gmail.com
  15. 15. Inner Beans• Remove the definition of Point bean and put into triangle bean• Remove the ref tag and put definition inside.• No performance adv.• whenever a bean is used for only one particular property, it’s advise to declare it as an inner bean rgupta.trainer@gmail.com
  16. 16. Aliases• alias giving name to same bean• Use alias tag• Now bean can be referred by new name rgupta.trainer@gmail.com
  17. 17. Spring bean scopes• In Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller.• In most cases, you may only deal with the Spring’s core scope – singleton and prototype, and the default scope is singleton. rgupta.trainer@gmail.com
  18. 18. Bean Scopes Scope Description Singleton (Default)Only one single instance will be created Prototype Creates any number of instances from a single bean configuration Request Scope of the bean instance will be limited to the Request life cycle Session Limited to session Global session Limited to global session- Portlet context.<bean name =“student” class =“Student” scope =“prototype”/> rgupta.trainer@gmail.com
  19. 19. Singleton scopectx.getBean(“student”) Spring Container Single student instance rgupta.trainer@gmail.com
  20. 20. Output in case ofdefault bean scope rgupta.trainer@gmail.com
  21. 21. Prototype scopectx.getBean(“student”) Spring Container Multiple Beans rgupta.trainer@gmail.com
  22. 22. rgupta.trainer@gmail.com
  23. 23. Spring Collection• What if member variable is collection major collection types are supported in Spring List – <list/> Set – <set/> Map – <map/> Properties – <props/> rgupta.trainer@gmail.com
  24. 24. Injecting list..rgupta.trainer@gmail.com
  25. 25. rgupta.trainer@gmail.com
  26. 26. Auto Wiring• Skip some of the configuration that we have to do by intelligent guessing what ref is• AKA shortcut.• Type of auto wiring – byName – byType (for only one composite object) – constructor rgupta.trainer@gmail.com
  27. 27. <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="tringle" class="com.ex3.code.Tringle" autowire="byName"></bean><bean id="pointA" class="com.ex3.code.Point"><property name="x" value="0"/><property name="y" value="0"/></bean><bean id="pointB" class="com.ex3.code.Point"><property name="x" value="20"/><property name="y" value="0"/></bean><bean id="pointC" class="com.ex3.code.Point"><property name="x" value="-20"/><property name="y" value="0"/></bean><alias name="tringle" alias="my-tringle"/></beans> rgupta.trainer@gmail.com
  28. 28. Aware interfaces..• BeanName Aware interface • Want to know the name of bean configured• ApplicationContextAware • Getting Application context • We need to implements ApplicationContextAware Container itself call setter related to aware interface before creation of any bean. rgupta.trainer@gmail.com
  29. 29. Bean Definition Inheritance• Lets say we have 100 bean definition in xml , lets we have common definition in each bean definition aka template rgupta.trainer@gmail.com
  30. 30. <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="parenttringle" class="com.ex3.code.Tringle"><property name="pointA" ref="firstPoint"></property></bean><bean id="tringle" class="com.ex3.code.Tringle" parent="parenttringle"><property name="pointC" ref="secPoint"></property><property name="pointC" ref="thirdPoint"></property></bean><bean id="firstPoint" class="com.ex3.code.Point"><property name="x" value="0"/><property name="y" value="0"/></bean><bean id="secPoint" class="com.ex3.code.Point"><property name="x" value="20"/><property name="y" value="0"/></bean><bean id="thirdPoint" class="com.ex3.code.Point"><property name="x" value="-20"/><property name="y" value="0"/></bean><alias name="tringle" alias="my-tringle"/></beans> rgupta.trainer@gmail.com
  31. 31. Lifecycle Callbacks• Spring provide us call-back method for life cycle of bean • for initialization of bean • for cleanup of beanEX: Shut down hook • closing app context for SE applications • use class AbstractAppicationContext, when main finishedAbstractApplicationContext ctx=new ClassPathXmlApplicationContext("springWithAutoWiring.xml");ctx.registerShutdownHook(); rgupta.trainer@gmail.com
  32. 32. cofig init and destroyed method• Choice I • implements InitializingBean,DisposableBean• Choice II • Dont want to bind to spring interface interfaces......<bean id="tringle" class="com.ex3.code.Tringle" autowire="byName" init-method="myInit" destroy- method="myDestroy">What happens if both are there? first spring then my method is called. rgupta.trainer@gmail.com
  33. 33. public class Tringle implements public void setPointC(Point pointC) { InitializingBean,DisposableBean{ this.pointC = pointC; }private Point pointA; public void draw() {private Point pointB; System.out.println(pointA); System.out.println(pointB);private Point pointC; System.out.println(pointC); }public Point getPointA() { @Overridereturn pointA; public void afterPropertiesSet() throws Exception { // TODO Auto-generated method stub} System.out.println("called after init of bean");public void setPointA(Point pointA) { } @Overridethis.pointA = pointA; public void destroy() throws Exception { System.out.println("called after destruction of bean");} }public Point getPointB() { }return pointB; }}public void setPointB(Point pointB) {this.pointB = pointB;}public Point getPointC() {return pointC;} rgupta.trainer@gmail.com
  34. 34. Method Injection – Method Replace class MobileStore{ public String buyMobile(){ return "Bought a Mobile Phone"; }}class MobileStoreReplacer implements MethodReplacer{ public Object reimplement(Object obj, Method method, Object[] args) throws Throwable{ return “Bought an iPhone”; }}<bean id =“mobileStore” class =“MobileStore”> <replace-method name =“buyMobile” replacer =“mobileStoreReplacer”/></bean><bean id =“mobileStoreReplacer” class =“MobileStoreReplacer”/> rgupta.trainer@gmail.com
  35. 35. Lookup Method Injectionpublic abstract class BookStore { public interface Book { public String bookTitle();public abstract Book orderBook(); }} Managed by Spring public class StoryBook implements Book{ public class ProgrammingBook public String bookTitle() { implements Book{ return "HarryPotter“; } public String bookTitle() { } return "spring programming“; } } • The ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container. rgupta.trainer@gmail.com
  36. 36. Thanks !!! rgupta.trainer@gmail.com

×