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

What's hot

Java spring framework
Java spring frameworkJava spring framework
Java spring framework
Rajiv Gupta
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
Dzmitry Naskou
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
John Lewis
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
Rajiv Srivastava
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
Mohit Gupta
 
Spring framework
Spring frameworkSpring framework
Spring framework
Rajkumar Singh
 
Spring Core
Spring CoreSpring Core
Spring Core
Pushan Bhattacharya
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
Hùng Nguyễn Huy
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
zeeshanhanif
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
John Lewis
 
Spring Framework Rohit
Spring Framework RohitSpring Framework Rohit
Spring Framework Rohit
Rohit Prabhakar
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
BG Java EE Course
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
Bozhidar Bozhanov
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
Aaron Schram
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
yuvalb
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
Santosh Kumar Kar
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
Manav Prasad
 
Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02
Guo Albert
 

What's hot (19)

Java spring framework
Java spring frameworkJava spring framework
Java spring framework
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
 
Spring Framework Rohit
Spring Framework RohitSpring Framework Rohit
Spring Framework Rohit
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02
 

Similar to Spring core

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Rajind Ruparathna
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
Dhiraj Champawat
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
AnushaNaidu
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
Spring framework
Spring frameworkSpring framework
Spring framework
Ajit Koti
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
Mindsmapped Consulting
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2
javatrainingonline
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
PawanMM
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
than sare
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf
DeoDuaNaoHet
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Z
sang nguyen
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
ealio
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
Guo Albert
 
Spring Basics
Spring BasicsSpring Basics
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Dineesha Suraweera
 
Spring Fa Qs
Spring Fa QsSpring Fa Qs
Spring Fa Qs
jbashask
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
Aneega
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
Muthuselvam RS
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
Lê Hảo
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1
Skillwise Group
 

Similar to Spring core (20)

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Z
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Fa Qs
Spring Fa QsSpring Fa Qs
Spring Fa Qs
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1
 

Recently uploaded

Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
christinelarrosa
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
Fwdays
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
UiPathCommunity
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Demystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through StorytellingDemystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through Storytelling
Enterprise Knowledge
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
Fwdays
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham HillinQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
LizaNolte
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 

Recently uploaded (20)

Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Demystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through StorytellingDemystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through Storytelling
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham HillinQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
inQuba Webinar Mastering Customer Journey Management with Dr Graham Hill
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 

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