SlideShare a Scribd company logo
SPRING IOC CONTAINER
HARSHIT CHOUDHARY
OUTLINE
 Inversion of Control explained
 Spring IOC Container
 Spring Bean
 Container Overview
 Spring Bean Configuration
 XML Based Spring Bean Configuration
 Annotation Based Spring Bean Configuration
 Java Based Spring Bean Configuration
HARSHIT CHOUDHARY
INVERSION OF CONTROL
HARSHIT CHOUDHARY
INVERSION OF CONTROL
 Object management inverted from Application Code to the Container
 A Design Pattern that says you do not create your objects but describe how they should be created.
 You don't directly connect your components and services together in code but describe which services are needed by which components in a
configuration file.
 Help achieve loose coupling between Object Dependencies
 Dependency Injection is a specialized form of Inversion of Control.
 Object Dependencies are injected by other assembler objects.
 Example of IOC is explained in the upcoming slides
HARSHIT CHOUDHARY
INVERSION OF CONTROL
HARSHIT CHOUDHARY
Class Diagram for a Registration Application, which may need to connect to different Databases.
INVERSION OF CONTROL (IOC)
HARSHIT CHOUDHARY
package com.training.spring;
public class RegistrationApp {
public static void main(String[] args) {
DBConnect dbcon = new MySQLConnection();
dbcon.connect();
}
}
package com.training.spring;
public class RegistrationApp {
public static void main(String[] args) {
DBConnect dbcon = new OracleConnection();
dbcon.connect();
}
}
Creating object of
corresponding DB class
INVERSION OF CONTROL (IOC)
HARSHIT CHOUDHARY
package com.training.spring;
public class RegistrationApp {
public static void main(String[] args) {
DBConnect dbcon = (DBConnect)Container.getComponent(args[0]);
if(dbcon !=null)
dbcon.connect();
}
}
IOC reverse the process of Object creation.
Container is going to provide us with the
required class object
INVERSION OF CONTROL (IOC)
HARSHIT CHOUDHARY
package com.training.spring;
public class Container {
private static Map<String, object> container;
public synchronized static Object getComponent(final String componentName) {
if (container == null) {
container = new HashMap<String, Object>();
}
Object result = container.get(componentName);
if (result == null) {
if ("mysql".equals(componentName)) {
result = new MySQLConnection();
} else if ("oracle".equals(componentName)) {
result = new OracleConnection();
} else if ("sqlserver".equals(componentName)) {
result = new SQLServerConnection();
}
if (result != null) {
container.put(componentName, result);
}
}
return result;
}
}
Container class Implementation
SUMMEDUP
 DI is a process whereby objects define their dependencies through constructor arguments, setters or
arguments to a factory method. The container then injects those dependencies when it creates the bean
 This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself
controlling the instantiation or location of its dependencies by using direct construction of classes, or a
mechanism such as the Service Locator pattern.
HARSHIT CHOUDHARY
WHAT DOES IOC DO?
• Create new objects
• Configure/solve dependency among objects and assemble them
• Allow objects to be retrieved by id/name
• Manage object’s lifecycle
• Allow external configuration
HARSHIT CHOUDHARY
WHY DO WE USE IOC?
• Achieve Loose coupling among Object Dependencies
• Reduce the amount of code in your application
• Does the plumbing work for you
• Application is more testable
• No more creating and hooking of objects together
• No more lookup
HARSHIT CHOUDHARY
SPRING IOC CONTAINER
HARSHIT CHOUDHARY
SPRING IOC CONTAINER
 Spring IOC Container is the program that injects dependencies into an object and make it
ready for use.
 Packages for Spring IOC container
 org.springframework.beans
 org.springframework.context
 2 types of IoC container implementation
 BeanFactory
 ApplicationContext
HARSHIT CHOUDHARY
BEAN FACTORY
 BeanFactory interface provides an advanced configuration mechanism capable of managing any type of
objects
 Provides the underlying basis for Spring’s IOC functionality.
 It is the root container that loads all the beans and provide dependency injection to enterprise
applications
 Now largely historical in nature for most users of Spring.
HARSHIT CHOUDHARY
APPLICATIONCONTEXT
 ApplicationContext is a subinterface of BeanFactory
 It adds easier integration with Spring AOP features, i18n, event publication, and application-layer specific
context
HARSHIT CHOUDHARY
USEFUL APPLICATIONCONTEXT IMPLEMENTATIONS
 AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using
annotations for Configuration, then we can use this to initialize the container and get the bean objects.
 ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone
application, then we can use this class to load the file and get the container object.
 FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the
xml configuration file can be loaded from anywhere in the file system.
 AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.
HARSHIT CHOUDHARY
BEANFACTORY OR APPLICATIONCONTEXT?
HARSHIT CHOUDHARY
Feature BeanFactory ApplicationContext
Bean instantiation/wiring Yes Yes
Automatic BeanPostProcessor registratio
n
No Yes
Automatic BeanFactoryPostProcessor reg
istration
No Yes
Convenient MessageSource access (for
i18n)
No Yes
ApplicationEvent publication No Yes
Use an ApplicationContext unless you have a good reason for not doing so.
SPRING BEANS
HARSHIT CHOUDHARY
SPRING BEANS
 The objects that form the backbone of the application and that are managed by Spring IOC Container
are called beans.
 A bean is an object that is instantiated, assembled and otherwise managed by a Spring IOC Container.
HARSHIT CHOUDHARY
BEAN SCOPES
 Singleton
 Default Scope
 Only one instance of the bean will be created for each container
 Prototype
 A new instance will be created every time the bean is requested
 Request
 Same as prototype scope, but is used in Web Applications.
 A new instance will be created for each HTTP request
 Session
 A new bean will be created for each HTTP Session by the container
 Global-session
 To create global session beans for Portlet applications
HARSHIT CHOUDHARY
SPRING BEAN CONFIGURATION
HARSHIT CHOUDHARY
SPRING BEAN CONFIGURATION
 Spring provides three ways to configure beans to be used in applications
 XML Based Configuration
 By creating Spring Configuration XML file to configure the beans.
 Annotation Based Configuration
 Spring 2.5 introduced support for annotation-based configuration metadata. Base Container is still XML.
 Java Based Configuration
 Starting from Spring 3.0, we can configure Spring beans using java programs. Pure Java-based configuration. No need for
having XML file for configuration Metadata
HARSHIT CHOUDHARY
XML-BASED CONFIGURATION METADATA
 Root element: <beans>
 The XML contains one or more <bean> elements
 id (or name) attribute to identify the bean
 class attribute to specify the fully qualified class
 By default, beans are treated as singletons
 Can also be prototypes (non singletons)
HARSHIT CHOUDHARY
XML-BASED CONFIGURATION METADATA
HARSHIT CHOUDHARY
The bean’s ID
The bean’s fully-
qualified classname
DEPENDENCY INJECTION
 Setter-Based
 Dependencies are assigned through JavaBeans properties (for example, setter methods)
 Constructor-Based
 Dependencies are provided as constructor parameters and are not exposed as JavaBeans
properties
 Method-Based
 The container is responsible for implementing methods at runtime
HARSHIT CHOUDHARY
SETTER INJECTION
HARSHIT CHOUDHARY
CONSTRUCTOR INJECTION
HARSHIT CHOUDHARY
CONSTRUCTOR ARGUMENT RESOLUTION
 Index
 Type
 Name
HARSHIT CHOUDHARY
WHICH ONE TO CHOOSE?
HARSHIT CHOUDHARY
POINTS IN FAVOR OF CONSTRUCTOR
• Constructor injection enforces a strong dependency contract. In short, a bean cannot be instantiated
without being given all of its dependencies. It is perfectly valid and ready to use upon instantiation.
• Because all of the bean’s dependencies are set through its constructor, there’s no need for superfluous
setter methods. This helps keep the lines of code at a minimum.
• By only allowing properties to be set through the constructor, you are, in effect, making those properties
immutable.
HARSHIT CHOUDHARY
POINTS IN FAVOR OF SETTER
• If a bean has several dependencies, the constructor’s parameter list can be quite lengthy.
• If there are several ways to construct a valid object, it can be hard to come up with unique constructors
since constructor signatures vary only by the number and type of parameters.
• If a constructor takes two or more parameters of the same type, it may be difficult to determine what
each parameter’s purpose is.
• Constructor injection does not lend itself readily to inheritance. A bean’s constructor will have to pass
parameters to super() in order to set private properties in the parent object.
HARSHIT CHOUDHARY
CONSTRUCTOR-BASED VS SETTER-BASED DI
 Tips : Use constructor arguments for mandatory dependencies and setters for optional dependencies
 More properties, more arguments to constructor
 Hence the Spring team generally advocates setter injection
HARSHIT CHOUDHARY
METHOD-BASED INJECTION
 Useful when a singleton bean needs to use a non-singleton bean
 Using CGLIB library, Spring generates dynamically a subclass and overrides the look up method
 Spring overrides the getEmployee() using lookup-method injection to provide a new instance of a Employee every time that method
is called
HARSHIT CHOUDHARY
METHOD BASED INJECTION
 Look-up method must be as follows
 <public|protected> [abstract] <return-type> theMethodName(no-arguments)
 We need an abstract method which will be configured as a lookup-method in the
configuration file.
 Spring will generate a proxy around which will implement the abstract method and return the
object of the target bean. Again used only if scopes of both the beans are different
 Also you must have the CGLIB jar(s) in your classpath
HARSHIT CHOUDHARY
AUTOWIRING COLLABORATORS
• Spring can resolve collaborators (other beans) automatically for your bean by
inspecting the contents of the ApplicationContext
• Advantages:
- Reduces the need to specify properties or constructor arguments
- New dependencies can be added to a class without changing the configuration
HARSHIT CHOUDHARY
AUTOWIRING MODES
HARSHIT CHOUDHARY
Mode Explanation
No (Default) No autowiring
byName Autowiring by property name. Spring looks for a bean with the
same name as the property that needs to be autowired
byType Allows a property to be autowired if exactly one bean of the
property type exists in the container. If more than one exists, a
fatal exception is thrown.
constructor Analogous to byType, but applies to constructor arguments.
autodetect If a default constructor with no argument is found, the
dependencies will be auto-wired by type. Otherwise, they will
be auto-wired by constructor
• Note : Autowiring works best when it is used consistently across a project
AUTOWIRING EXAMPLE
HARSHIT CHOUDHARY
Autowire by Name
Autowire by Type
AUTOWIRING EXAMPLE
HARSHIT CHOUDHARY
Autowire Constructor
LIFECYCLE OF BEANS
HARSHIT CHOUDHARY
LIFECYCLE CALLBACKS
 Three ways to interact with the container’s bean lifecycle management
 By implementing the InitializingBean and DisposableBean interfaces
 Using init-method and destroy-method attributes in the bean definition
(if you don’t want your classes coupled to Spring interfaces)
 @PostConstruct and @PreDestroy annotations (More on this later)
HARSHIT CHOUDHARY
INITIALIZATION CALLBACKS
• Implement the InitializingBean interface and override afterPropertiesSet() method
• Container calls this method upon initialization of your beans
• Alternatively specify a POJO initialization using the init-method attribute
HARSHIT CHOUDHARY
public class Employee implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}}
public class Employee {
public void init() {
// do some initialization work
}
}
<bean id=“emp” class=“com.example.lifecycle.Employee“ init-method="init"/>
DESTRUCTION CALLBACKS
• Implement the DisposableBean interface and override destroy() method
• Container calls this method upon destruction of your beans
 Alternatively specify a POJO initialization using destroy-method attribute
HARSHIT CHOUDHARY
public class Employee implements DisposableBean{
public void destroy() {
//do some destruction work (like releasing pooled connections) }
}
public class Employee {
public void cleanup() {
// do some destruction work
}
}
<bean id=“emp" class=“com.example.lifecycle.Employee“ destroy-method="cleanup"/>
ANNOTATION BASED CONTAINER CONFIGURATION
HARSHIT CHOUDHARY
TO CONFIGURE SPRING - ANNOTATION VS XML
 Annotations
+ More concise configuration
+ Wiring is more close to the source
- Configuration becomes decentralized and harder to control
 XML
+ Wiring done without touching source code or recompiling
+ A centralized location for configuration
- Can become verbose
 It is up to the developer to decide the strategy that suits better
HARSHIT CHOUDHARY
CAN WE USE BOTH?
 Spring supports mix of both
 But Annotation injection is performed before XML injection
 Hence XML-based injection will override Annotation-based injection for properties wired through both
approaches
HARSHIT CHOUDHARY
ANNOTATIONS INTRODUCED IN SPRING
 Spring 2.0
 @Required
 Spring 2.5
 @Autowired
 @Resource, @PostConstruct, @PreDestroy
 Spring 3.0
 @Inject, @Qualifier, @Named, and @Provider
HARSHIT CHOUDHARY
@REQUIRED
• Applies to bean property setter methods
• Indicates that the affected bean property must be populated at configuration time
• Throws an exception if it has not been set
HARSHIT CHOUDHARY
@Required use. Must use
setter injection to set the
value
@AUTOWIRED
 Can be used in the Java source code for specifying DI requirement
 Places where @Autowired can be used
 Fields
 Setter methods
 Constructor methods
 Arbitrary methods
 Need to include the below element in the bean configuration file to use this
 <context:annotation-config>
HARSHIT CHOUDHARY
 Because autowiring by type may lead to multiple candidates, it is necessary to have more control over
the selection process
 One way to accomplish this is with Spring's @Qualifier annotation.
HARSHIT CHOUDHARY
Of all the beans of Address
class, it uses one matching the
address1 id.
@Qualifier can be used with
parameter names as well.
@RESOURCE
 Spring also supports injection using the @Resource on fields or bean property setter methods
 It takes a 'name' attribute, and by default Spring will interpret that value as the bean name to be injected
i.e., it follows by-name semantics
HARSHIT CHOUDHARY
Must have a bean with
id – address1 of type
Address defined in
config file.
@POSTCONSTRUCT AND @PREDESTROY
 An alternative to initialization callbacks and destruction callbacks
HARSHIT CHOUDHARY
JAVA BASED CONTAINER CONFIGURATION
HARSHIT CHOUDHARY
@CONFIGURATION AND @BEAN
 Class with @Configuration indicates that the class can be used as a source of bean definitions
 @Bean-annotated methods define instantiation, configuration, and initialization logic for objects to be
managed by the Spring IoC container
 This is equivalent to
HARSHIT CHOUDHARY
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
} }
<beans>
<bean id="myService" class=“MyServiceImpl"/>
</beans>
ANNOTATIONCONFIGAPPLICATIONCONTEXT
 An ApplicationContext implementation
 Uses @Configuration classes as input
HARSHIT CHOUDHARY
public static void main(String[] args) {
ApplicationContext ctx = new
AnnotationConfigApplicationContext(AppConfig.class);
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}
@CONFIGURATION AND @BEAN
HARSHIT CHOUDHARY
@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
return new TransferServiceImpl(accountRepository());
}
@Bean
public AccountRepository accountRepository() {
return new InMemoryAccountRepository();
} }
<bean id = "accountRepository"
class = “InMemoryAccountRepository“></bean>
<bean id = "transferService“ class = “TransferServiceImpl">
<property name="accountRepository" ref="accountRepository"/>
</bean>
This is same as:
SCANNING COMPONENTS FROM CLASSPATH
HARSHIT CHOUDHARY
SCANNING COMPONENTS FROM THE CLASSPATH
 So far the “base" bean definitions are explicitly defined in the XML file, while the annotations only drive the
dependency injection
 But Component Scanning avoids manual configuration
 It can automatically scan, detect, and instantiate your components with particular stereotype annotations from
the classpath
 The basic annotation denoting a Spring-managed component is @Component
 Other stereotypes include @Repository, @Service, and @Controller denoting components in the persistence,
service, and presentation layers, respectively
HARSHIT CHOUDHARY
AUTOMATICALLY DETECTING CLASSES AND REGISTERING BEAN
DEFINITIONS
HARSHIT CHOUDHARY
To Add in Configuration XML File other than DataSource
Configuartion common parent package for the two classes

More Related Content

PPTX
Spring jdbc
PPTX
Spring aop
PPTX
Spring framework in depth
PDF
Spring mvc
PDF
Spring Framework
PDF
Rest web service
PPTX
Spring 3.x - Spring MVC - Advanced topics
Spring jdbc
Spring aop
Spring framework in depth
Spring mvc
Spring Framework
Rest web service
Spring 3.x - Spring MVC - Advanced topics

What's hot (19)

PDF
Java spring framework
PDF
Spring Framework - MVC
ODP
Annotation-Based Spring Portlet MVC
PDF
Spring annotation
PPTX
Spring MVC framework
PPTX
Spring framework
PPT
Spring Core
PDF
Spring MVC Framework
PPTX
Spring Web MVC
PPSX
Spring - Part 1 - IoC, Di and Beans
ODP
Spring Portlet MVC
PPTX
Spring Framework Rohit
PPT
Java Server Faces (JSF) - Basics
PPT
Spring MVC Basics
PDF
Spring MVC
PPT
Spring MVC
PPTX
Spring & hibernate
PPT
Spring introduction
PDF
Spring bean mod02
Java spring framework
Spring Framework - MVC
Annotation-Based Spring Portlet MVC
Spring annotation
Spring MVC framework
Spring framework
Spring Core
Spring MVC Framework
Spring Web MVC
Spring - Part 1 - IoC, Di and Beans
Spring Portlet MVC
Spring Framework Rohit
Java Server Faces (JSF) - Basics
Spring MVC Basics
Spring MVC
Spring MVC
Spring & hibernate
Spring introduction
Spring bean mod02
Ad

Similar to Spring core (20)

PDF
Introduction to Spring Framework
PPTX
PPTX
Spring framework
PPT
Spring talk111204
PPT
Hybernat and structs, spring classes in mumbai
PPTX
Spring Basics
PPTX
Spring (1)
PDF
Manual tutorial-spring-java
PDF
Spring Reference
PPTX
Spring essentials 1 (Spring Series 01)
PPTX
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
PPT
Spring, web service, web server, eclipse by a introduction sandesh sharma
PPT
Spring framework
PDF
Spring Reference
PDF
2-0. Spring ecosytem.pdf
PDF
Overview chap1
PPTX
Session 43 - Spring - Part 1 - IoC DI Beans
PPTX
Brownbag001 spring ioc from 2012
PPT
Spring overview &amp; architecture
PPTX
Introduction to Spring
Introduction to Spring Framework
Spring framework
Spring talk111204
Hybernat and structs, spring classes in mumbai
Spring Basics
Spring (1)
Manual tutorial-spring-java
Spring Reference
Spring essentials 1 (Spring Series 01)
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Spring, web service, web server, eclipse by a introduction sandesh sharma
Spring framework
Spring Reference
2-0. Spring ecosytem.pdf
Overview chap1
Session 43 - Spring - Part 1 - IoC DI Beans
Brownbag001 spring ioc from 2012
Spring overview &amp; architecture
Introduction to Spring
Ad

Recently uploaded (20)

PPTX
Tartificialntelligence_presentation.pptx
PPT
Teaching material agriculture food technology
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
A Presentation on Artificial Intelligence
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
1. Introduction to Computer Programming.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Approach and Philosophy of On baking technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Electronic commerce courselecture one. Pdf
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Tartificialntelligence_presentation.pptx
Teaching material agriculture food technology
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Encapsulation_ Review paper, used for researhc scholars
Programs and apps: productivity, graphics, security and other tools
A Presentation on Artificial Intelligence
“AI and Expert System Decision Support & Business Intelligence Systems”
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Spectral efficient network and resource selection model in 5G networks
1. Introduction to Computer Programming.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Approach and Philosophy of On baking technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Advanced methodologies resolving dimensionality complications for autism neur...
Network Security Unit 5.pdf for BCA BBA.
Electronic commerce courselecture one. Pdf
SOPHOS-XG Firewall Administrator PPT.pptx
Spectroscopy.pptx food analysis technology
The Rise and Fall of 3GPP – Time for a Sabbatical?

Spring core

  • 2. OUTLINE  Inversion of Control explained  Spring IOC Container  Spring Bean  Container Overview  Spring Bean Configuration  XML Based Spring Bean Configuration  Annotation Based Spring Bean Configuration  Java Based Spring Bean Configuration HARSHIT CHOUDHARY
  • 4. INVERSION OF CONTROL  Object management inverted from Application Code to the Container  A Design Pattern that says you do not create your objects but describe how they should be created.  You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file.  Help achieve loose coupling between Object Dependencies  Dependency Injection is a specialized form of Inversion of Control.  Object Dependencies are injected by other assembler objects.  Example of IOC is explained in the upcoming slides HARSHIT CHOUDHARY
  • 5. INVERSION OF CONTROL HARSHIT CHOUDHARY Class Diagram for a Registration Application, which may need to connect to different Databases.
  • 6. INVERSION OF CONTROL (IOC) HARSHIT CHOUDHARY package com.training.spring; public class RegistrationApp { public static void main(String[] args) { DBConnect dbcon = new MySQLConnection(); dbcon.connect(); } } package com.training.spring; public class RegistrationApp { public static void main(String[] args) { DBConnect dbcon = new OracleConnection(); dbcon.connect(); } } Creating object of corresponding DB class
  • 7. INVERSION OF CONTROL (IOC) HARSHIT CHOUDHARY package com.training.spring; public class RegistrationApp { public static void main(String[] args) { DBConnect dbcon = (DBConnect)Container.getComponent(args[0]); if(dbcon !=null) dbcon.connect(); } } IOC reverse the process of Object creation. Container is going to provide us with the required class object
  • 8. INVERSION OF CONTROL (IOC) HARSHIT CHOUDHARY package com.training.spring; public class Container { private static Map<String, object> container; public synchronized static Object getComponent(final String componentName) { if (container == null) { container = new HashMap<String, Object>(); } Object result = container.get(componentName); if (result == null) { if ("mysql".equals(componentName)) { result = new MySQLConnection(); } else if ("oracle".equals(componentName)) { result = new OracleConnection(); } else if ("sqlserver".equals(componentName)) { result = new SQLServerConnection(); } if (result != null) { container.put(componentName, result); } } return result; } } Container class Implementation
  • 9. SUMMEDUP  DI is a process whereby objects define their dependencies through constructor arguments, setters or arguments to a factory method. The container then injects those dependencies when it creates the bean  This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern. HARSHIT CHOUDHARY
  • 10. WHAT DOES IOC DO? • Create new objects • Configure/solve dependency among objects and assemble them • Allow objects to be retrieved by id/name • Manage object’s lifecycle • Allow external configuration HARSHIT CHOUDHARY
  • 11. WHY DO WE USE IOC? • Achieve Loose coupling among Object Dependencies • Reduce the amount of code in your application • Does the plumbing work for you • Application is more testable • No more creating and hooking of objects together • No more lookup HARSHIT CHOUDHARY
  • 13. SPRING IOC CONTAINER  Spring IOC Container is the program that injects dependencies into an object and make it ready for use.  Packages for Spring IOC container  org.springframework.beans  org.springframework.context  2 types of IoC container implementation  BeanFactory  ApplicationContext HARSHIT CHOUDHARY
  • 14. BEAN FACTORY  BeanFactory interface provides an advanced configuration mechanism capable of managing any type of objects  Provides the underlying basis for Spring’s IOC functionality.  It is the root container that loads all the beans and provide dependency injection to enterprise applications  Now largely historical in nature for most users of Spring. HARSHIT CHOUDHARY
  • 15. APPLICATIONCONTEXT  ApplicationContext is a subinterface of BeanFactory  It adds easier integration with Spring AOP features, i18n, event publication, and application-layer specific context HARSHIT CHOUDHARY
  • 16. USEFUL APPLICATIONCONTEXT IMPLEMENTATIONS  AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.  ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.  FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.  AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications. HARSHIT CHOUDHARY
  • 17. BEANFACTORY OR APPLICATIONCONTEXT? HARSHIT CHOUDHARY Feature BeanFactory ApplicationContext Bean instantiation/wiring Yes Yes Automatic BeanPostProcessor registratio n No Yes Automatic BeanFactoryPostProcessor reg istration No Yes Convenient MessageSource access (for i18n) No Yes ApplicationEvent publication No Yes Use an ApplicationContext unless you have a good reason for not doing so.
  • 19. SPRING BEANS  The objects that form the backbone of the application and that are managed by Spring IOC Container are called beans.  A bean is an object that is instantiated, assembled and otherwise managed by a Spring IOC Container. HARSHIT CHOUDHARY
  • 20. BEAN SCOPES  Singleton  Default Scope  Only one instance of the bean will be created for each container  Prototype  A new instance will be created every time the bean is requested  Request  Same as prototype scope, but is used in Web Applications.  A new instance will be created for each HTTP request  Session  A new bean will be created for each HTTP Session by the container  Global-session  To create global session beans for Portlet applications HARSHIT CHOUDHARY
  • 22. SPRING BEAN CONFIGURATION  Spring provides three ways to configure beans to be used in applications  XML Based Configuration  By creating Spring Configuration XML file to configure the beans.  Annotation Based Configuration  Spring 2.5 introduced support for annotation-based configuration metadata. Base Container is still XML.  Java Based Configuration  Starting from Spring 3.0, we can configure Spring beans using java programs. Pure Java-based configuration. No need for having XML file for configuration Metadata HARSHIT CHOUDHARY
  • 23. XML-BASED CONFIGURATION METADATA  Root element: <beans>  The XML contains one or more <bean> elements  id (or name) attribute to identify the bean  class attribute to specify the fully qualified class  By default, beans are treated as singletons  Can also be prototypes (non singletons) HARSHIT CHOUDHARY
  • 24. XML-BASED CONFIGURATION METADATA HARSHIT CHOUDHARY The bean’s ID The bean’s fully- qualified classname
  • 25. DEPENDENCY INJECTION  Setter-Based  Dependencies are assigned through JavaBeans properties (for example, setter methods)  Constructor-Based  Dependencies are provided as constructor parameters and are not exposed as JavaBeans properties  Method-Based  The container is responsible for implementing methods at runtime HARSHIT CHOUDHARY
  • 28. CONSTRUCTOR ARGUMENT RESOLUTION  Index  Type  Name HARSHIT CHOUDHARY
  • 29. WHICH ONE TO CHOOSE? HARSHIT CHOUDHARY
  • 30. POINTS IN FAVOR OF CONSTRUCTOR • Constructor injection enforces a strong dependency contract. In short, a bean cannot be instantiated without being given all of its dependencies. It is perfectly valid and ready to use upon instantiation. • Because all of the bean’s dependencies are set through its constructor, there’s no need for superfluous setter methods. This helps keep the lines of code at a minimum. • By only allowing properties to be set through the constructor, you are, in effect, making those properties immutable. HARSHIT CHOUDHARY
  • 31. POINTS IN FAVOR OF SETTER • If a bean has several dependencies, the constructor’s parameter list can be quite lengthy. • If there are several ways to construct a valid object, it can be hard to come up with unique constructors since constructor signatures vary only by the number and type of parameters. • If a constructor takes two or more parameters of the same type, it may be difficult to determine what each parameter’s purpose is. • Constructor injection does not lend itself readily to inheritance. A bean’s constructor will have to pass parameters to super() in order to set private properties in the parent object. HARSHIT CHOUDHARY
  • 32. CONSTRUCTOR-BASED VS SETTER-BASED DI  Tips : Use constructor arguments for mandatory dependencies and setters for optional dependencies  More properties, more arguments to constructor  Hence the Spring team generally advocates setter injection HARSHIT CHOUDHARY
  • 33. METHOD-BASED INJECTION  Useful when a singleton bean needs to use a non-singleton bean  Using CGLIB library, Spring generates dynamically a subclass and overrides the look up method  Spring overrides the getEmployee() using lookup-method injection to provide a new instance of a Employee every time that method is called HARSHIT CHOUDHARY
  • 34. METHOD BASED INJECTION  Look-up method must be as follows  <public|protected> [abstract] <return-type> theMethodName(no-arguments)  We need an abstract method which will be configured as a lookup-method in the configuration file.  Spring will generate a proxy around which will implement the abstract method and return the object of the target bean. Again used only if scopes of both the beans are different  Also you must have the CGLIB jar(s) in your classpath HARSHIT CHOUDHARY
  • 35. AUTOWIRING COLLABORATORS • Spring can resolve collaborators (other beans) automatically for your bean by inspecting the contents of the ApplicationContext • Advantages: - Reduces the need to specify properties or constructor arguments - New dependencies can be added to a class without changing the configuration HARSHIT CHOUDHARY
  • 36. AUTOWIRING MODES HARSHIT CHOUDHARY Mode Explanation No (Default) No autowiring byName Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired byType Allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown. constructor Analogous to byType, but applies to constructor arguments. autodetect If a default constructor with no argument is found, the dependencies will be auto-wired by type. Otherwise, they will be auto-wired by constructor • Note : Autowiring works best when it is used consistently across a project
  • 40. LIFECYCLE CALLBACKS  Three ways to interact with the container’s bean lifecycle management  By implementing the InitializingBean and DisposableBean interfaces  Using init-method and destroy-method attributes in the bean definition (if you don’t want your classes coupled to Spring interfaces)  @PostConstruct and @PreDestroy annotations (More on this later) HARSHIT CHOUDHARY
  • 41. INITIALIZATION CALLBACKS • Implement the InitializingBean interface and override afterPropertiesSet() method • Container calls this method upon initialization of your beans • Alternatively specify a POJO initialization using the init-method attribute HARSHIT CHOUDHARY public class Employee implements InitializingBean { public void afterPropertiesSet() { // do some initialization work }} public class Employee { public void init() { // do some initialization work } } <bean id=“emp” class=“com.example.lifecycle.Employee“ init-method="init"/>
  • 42. DESTRUCTION CALLBACKS • Implement the DisposableBean interface and override destroy() method • Container calls this method upon destruction of your beans  Alternatively specify a POJO initialization using destroy-method attribute HARSHIT CHOUDHARY public class Employee implements DisposableBean{ public void destroy() { //do some destruction work (like releasing pooled connections) } } public class Employee { public void cleanup() { // do some destruction work } } <bean id=“emp" class=“com.example.lifecycle.Employee“ destroy-method="cleanup"/>
  • 43. ANNOTATION BASED CONTAINER CONFIGURATION HARSHIT CHOUDHARY
  • 44. TO CONFIGURE SPRING - ANNOTATION VS XML  Annotations + More concise configuration + Wiring is more close to the source - Configuration becomes decentralized and harder to control  XML + Wiring done without touching source code or recompiling + A centralized location for configuration - Can become verbose  It is up to the developer to decide the strategy that suits better HARSHIT CHOUDHARY
  • 45. CAN WE USE BOTH?  Spring supports mix of both  But Annotation injection is performed before XML injection  Hence XML-based injection will override Annotation-based injection for properties wired through both approaches HARSHIT CHOUDHARY
  • 46. ANNOTATIONS INTRODUCED IN SPRING  Spring 2.0  @Required  Spring 2.5  @Autowired  @Resource, @PostConstruct, @PreDestroy  Spring 3.0  @Inject, @Qualifier, @Named, and @Provider HARSHIT CHOUDHARY
  • 47. @REQUIRED • Applies to bean property setter methods • Indicates that the affected bean property must be populated at configuration time • Throws an exception if it has not been set HARSHIT CHOUDHARY @Required use. Must use setter injection to set the value
  • 48. @AUTOWIRED  Can be used in the Java source code for specifying DI requirement  Places where @Autowired can be used  Fields  Setter methods  Constructor methods  Arbitrary methods  Need to include the below element in the bean configuration file to use this  <context:annotation-config> HARSHIT CHOUDHARY
  • 49.  Because autowiring by type may lead to multiple candidates, it is necessary to have more control over the selection process  One way to accomplish this is with Spring's @Qualifier annotation. HARSHIT CHOUDHARY Of all the beans of Address class, it uses one matching the address1 id. @Qualifier can be used with parameter names as well.
  • 50. @RESOURCE  Spring also supports injection using the @Resource on fields or bean property setter methods  It takes a 'name' attribute, and by default Spring will interpret that value as the bean name to be injected i.e., it follows by-name semantics HARSHIT CHOUDHARY Must have a bean with id – address1 of type Address defined in config file.
  • 51. @POSTCONSTRUCT AND @PREDESTROY  An alternative to initialization callbacks and destruction callbacks HARSHIT CHOUDHARY
  • 52. JAVA BASED CONTAINER CONFIGURATION HARSHIT CHOUDHARY
  • 53. @CONFIGURATION AND @BEAN  Class with @Configuration indicates that the class can be used as a source of bean definitions  @Bean-annotated methods define instantiation, configuration, and initialization logic for objects to be managed by the Spring IoC container  This is equivalent to HARSHIT CHOUDHARY @Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); } } <beans> <bean id="myService" class=“MyServiceImpl"/> </beans>
  • 54. ANNOTATIONCONFIGAPPLICATIONCONTEXT  An ApplicationContext implementation  Uses @Configuration classes as input HARSHIT CHOUDHARY public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); MyService myService = ctx.getBean(MyService.class); myService.doStuff(); }
  • 55. @CONFIGURATION AND @BEAN HARSHIT CHOUDHARY @Configuration public class AppConfig { @Bean public TransferService transferService() { return new TransferServiceImpl(accountRepository()); } @Bean public AccountRepository accountRepository() { return new InMemoryAccountRepository(); } } <bean id = "accountRepository" class = “InMemoryAccountRepository“></bean> <bean id = "transferService“ class = “TransferServiceImpl"> <property name="accountRepository" ref="accountRepository"/> </bean> This is same as:
  • 56. SCANNING COMPONENTS FROM CLASSPATH HARSHIT CHOUDHARY
  • 57. SCANNING COMPONENTS FROM THE CLASSPATH  So far the “base" bean definitions are explicitly defined in the XML file, while the annotations only drive the dependency injection  But Component Scanning avoids manual configuration  It can automatically scan, detect, and instantiate your components with particular stereotype annotations from the classpath  The basic annotation denoting a Spring-managed component is @Component  Other stereotypes include @Repository, @Service, and @Controller denoting components in the persistence, service, and presentation layers, respectively HARSHIT CHOUDHARY
  • 58. AUTOMATICALLY DETECTING CLASSES AND REGISTERING BEAN DEFINITIONS HARSHIT CHOUDHARY To Add in Configuration XML File other than DataSource Configuartion common parent package for the two classes