Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
BY
PUSHAN BHATTACHARYA
Its time for
1
Pushan Bhattacharya
Agenda – what to do in this Spring
Dependency Injection
Overview of Spring Framework
Various injections and their usages in detail
Bean scope
Bean wiring
Inner bean
Bean properties
Bean life cycle
Bean auto wiring
Spring Annotation
2
Pushan Bhattacharya
High Dependency = High Responsibility
public class Tiger {
public void eat() {
System.out.println(“Do not
disturb”);
}
}
public class MainClass {
public static void main(String…
args) {
Tiger t = new Tiger();
t.eat();
}
}
3
o Requirement: Change Tiger to
Lion.
o Me: Urggghhh. Too many
changes.
1. Standalone Lion class
2. Change the object
declaration to Lion
3. Change the reference
4. Compile again
5. Test
Pushan Bhattacharya
A bit less dependency
public interface Animal {
void eat();
}
public class Tiger implements Animal {
@Override
public void eat() {
System.out.println(“Do not disturb”);
}
}
public class MainClass {
public static void main(String… args) {
Animal a = new Tiger();
a.eat();
}
}
4
o Requirement: Change Tiger to
Lion.
o Me: Ufff. Again some changes.
1. Lion implements Animal
2. Change the object
declaration to Lion
3. Change the reference
4. Compile again
5. Test
Pushan Bhattacharya
Dependency Injection
public interface Animal {
void eat();
}
public class Tiger implements Animal {
@Override
public void eat() {
System.out.println(“Do not disturb”);
}
}
public class MainClass {
public static void main(String… args) {
ApplicationContext aC = new ClassPathXmlApplicationContext(“wildLife.xml”);
Animal a = (Animal) aC.getBean(“animal”);
a.eat();
}
}
wildLife.xml
<bean id = “animal” class = “Tiger” />
5
o Requirement: Change Tiger to
Lion.
o Me: Ok. Small change.
1. Lion implements Animal
2. Change bean class to Lion
3. Change the reference
4. Compile again
5. Test
Pushan Bhattacharya
So what is Spring?
IoC container
Lightweight framework
Fully modularized (High decoupling)
Considered an alternative / replacement for the
Enterprise JavaBean (EJB) model
Flexible
 Programmers decide how to program
Not exclusive to Java (e.g. .NET)
Solutions to typical coding busywork
 JDBC
 LDAP
 Web Services
6
Pushan Bhattacharya
What Spring offers?
Dependency Injection (DI)
 DI is implemented through IoC (Inversion of Control)
Aspect Oriented Programming
 Runtime injection-based
Portable Service Abstractions
 The rest of spring
 ORM, DAO, Web MVC, Web, etc.
 Allows access to these without knowing how they actually work
Easily testable
7
Pushan Bhattacharya
What is a bean?
A Bean is a class that has only state but no behavior
A Bean must contain a no-argument constructor
A Bean should be serialized
8
Class Bean
Pushan Bhattacharya
Spring Framework Architecture
9
Pushan Bhattacharya
SPRING CORE CONTAINER
T
E
S
T
BeansCore Context
Expression
Language
DATA ACCESS
INTEGRATION
Spring ORM
Spring DAO
WEB LAYER
Spring WEB
Services
SPRING WEB
MVC
FRAMEWORK
SPRING
AOP
Spring Bean Configuration
10
Pushan Bhattacharya
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd“ >
<bean id = “animal” class = “com.pushan.spring.beans.Tiger“ >
<property name = “msg” value = “Eating now“ />
</bean>
<!--
.
.
.
-->
</beans>
Spring IoC Container
11
Pushan Bhattacharya
Bean / POJO /
Application Class
Bean Configuration
Metadata
Completely Configured
Application
Ready to Use
Spring IoC
Container
Registered
Input
Output
1
2
3
Spring IoC Container contd…
12
BeanFactory ApplicationContext
The simplest factory, mainly for DI The advanced and more complex factory
Used when resources are limited, e.g., mobile,
applets etc.
Used elsewhere and has the below features,
1> Enterprise aware functions
2> Publish application events to listeners
3> Wire and dispose beans on request
org.springframework.beans.factory.BeanFactory org.springframework.context.ApplicationContext
XmlBeanFactory factory = new
XmlBeanFactory (new
ClassPathResource(“wildLife.xml"));
ApplicationContext aC = new
ClassPathXmlApplicationContext(“wildLi
fe.xml”);
Pushan Bhattacharya
Injection Methods
Setter Injection
 Pass dependencies in via property setters (e.g., Spring)
Constructor Injection
 Pass dependencies in via constructor (e.g., Spring)
Interface Injection
 Pass dependencies in via interfaces (e.g., Avalon)
13
public class MainClass {
public static void main(String…
args) {
ApplicationContext aC = new
ClassPathXmlApplicationContext(“wild
Life.xml”);
Animal a = (Animal)
aC.getBean(“animal”);
a.eat();
wildLife.xml
<bean id = “animal” class
= “Tiger” />
Pushan Bhattacharya
Setter Injection
In the <bean>, Specify <property> tag.
14
public class College {
private String collegeId;
private int totalStudents;
public String getCollegeId() {
return collegeId;
}
public void setCollegeId(String
collegeId) {
this.collegeId = collegeId;
}
public int getTotalStudents() {
return totalStudents;
}
public void setTotalStudents(int
totalStudents) {
this.totalStudents =
totalStudents;
}
public class MyClass {
private static final String MY_COLLEGE =
"myCollege";
public static void main(String... args) {
ApplicationContext ctx = new
ClassPathXmlApplicationContext("springConfig.xml"
College col = (College) ctx.getBean(MY_COLLEGE);
System.out.println("College Id: " +
col.getCollegeId());
System.out.println("Total Students: " +
col.getTotalStudents());
}
}
<bean id="myCollege"
class="com.pushan.study.spring.beans.College"
>
<property name="collegeId"
value="123Abc"/>
<property name="totalStudents"
Pushan Bhattacharya
Constructor Injection
15
In the <bean>, Specify <constructor-arg>
public class College {
private String collegeId;
private int
totalStudents;
public void College (int
tS, String cI) {
this.totalStudents = tS;
this.collegeId = cI;
}
public String
getCollegeId(){
return collegeId;
}
public int
getTotalStudents() {
return totalStudents;
public class MyClass {
private static final String MY_COLLEGE =
"myCollege";
public static void main(String... args) {
ApplicationContext ctx = new
ClassPathXmlApplicationContext("springConfig.xml
");
College col = (College) ctx.getBean(MY_COLLEGE);
System.out.println("College Id: " +
col.getCollegeId());
System.out.println("Total Students: " +
col.getTotalStudents());
}
}
<bean id="myCollege"
class="com.pushan.study.spring.beans.College"
>
<constructor-arg type=“int” value=“500”/>
<constructor-arg type=“java.lang.String”
value=“123Abc”/>
Pushan Bhattacharya
Constructor Injection Illustrated
The ‘value’ attribute is mandatory and rest are
optional, e.g., ‘type’
Constructor Injection can automatically cast the
value to the desired ‘known’ type
By default the ‘type’ of the ‘value’ is ‘java.lang.String’
(if not specified explicitly)
Constructor injection does not interpret ordering of
the arguments specified
16
Pushan Bhattacharya
Constructor Injection Ambiguity 1
17
<bean id="myCollege" class="com.pushan.College">
<constructor-arg value=“500”/>
<constructor-arg value=“123Abc”/>
</bean>
public class College {
private String collegeId;
private int totalStudents;
private String collegeAdd;
public College (int totalStudents, String collegeId){
this.totalStudents = totalStudents;
this.collegeId = collegeId;
}
public College (String collegeAdd, String collegeId){
this.collegeAdd = collegeAdd;
this.collegeId = collegeId;
}
}
Which constructor will be called?
Pushan Bhattacharya
Constructor Injection Ambiguity 1 Solution
18
<bean id="myCollege" class="com.pushan.College">
<constructor-arg value=“500” type=“int”/>
<constructor-arg value=“123Abc” type=“java.lang.String”/>
</bean>
The ‘type’ of the value is specified
public class College {
private String collegeId;
private int totalStudents;
private String collegeAdd;
public College (int totalStudents, String collegeId){
this.totalStudents = totalStudents;
this.collegeId = collegeId;
}
public College (String collegeAdd, String collegeId){
this.collegeAdd = collegeAdd;
this.collegeId = collegeId;
}
}
Pushan Bhattacharya
Constructor Injection Ambiguity 2
19
<bean id="myCollege" class="com.pushan.College">
<constructor-arg value=“500” type=“int”/>
<constructor-arg value=“123Abc” type=“java.lang.String”/>
</bean>
public class College {
private String collegeId;
private int totalStudents;
private String collegeAdd;
public College (int totalStudents, String collegeId){
this.totalStudents = totalStudents;
this.collegeId = collegeId;
}
public College (String collegeAdd, int totalStudents){
this.totalStudents = totalStudents;
this. collegeAdd = collegeAdd;
}
}
Which constructor will be called?
Pushan Bhattacharya
Constructor Injection Ambiguity 2 Solution
20
The ‘index’ of the value is specified
<bean id="myCollege" class="com.pushan.College">
<constructor-arg value=“500” type=“int” index=“0”/>
<constructor-arg value=“123Abc” type=“java.lang.String” index=“1”/>
</bean>
public class College {
private String collegeId;
private int totalStudents;
private String collegeAdd;
public College (int totalStudents, String collegeId){
this.totalStudents = totalStudents;
this.collegeId = collegeId;
}
public College (String collegeAdd, int totalStudents){
this.totalStudents = totalStudents;
this. collegeAdd = collegeAdd;
}
}
Pushan Bhattacharya
Bean Scope 1 – Object Type (Part I)
Pushan Bhattacharya
21
Bean Scope Description
singleton Single instance of bean in every getBean() call [Default]
prototype New instance of bean in every getBean() call
request Single instance of bean per HTTP request
session Single instance of bean per HTTP session
global-session Single instance of bean per global HTTP session
thread Single instance of bean per thread
custom Customized scope
Valid in the context of
web-aware
ApplicationContext
Added in Spring 3.0
We will look into
‘singleton’ and
‘prototype’ scopes
only
Bean Scope 1 – Object Type (Part II)
Mainly bean can be of two types, viz.,
1. Singleton (e.g., <bean scope=“singleton” … />)
2. Prototype (e.g., <bean scope=“prototype” … />)
A ‘singleton’ bean is created once in the Spring container.
This ‘singleton’ bean is given every time when referred. It is
garbage collected when the container shuts down.
A ‘prototype’ bean means a new object in every request. It is
garbage collected in the normal way, i.e., when there is no
reference for this object.
By default every bean is singleton if not specified explicitly.
22
Pushan Bhattacharya
Bean Scope 2 - Inheritance
23
<bean id="a" class=“A” >
<property name="msg1" value="Tiger runs" />
<property name="msg2" value="Tiger eats" />
</bean>
<bean id="b" class="B" parent="a">
<property name="msg1" value="Lion runs" />
<property name="msg3" value="Lion sleeps" />
</bean>
public class A {
private String msg1;
private String msg2;
// getters and setters ...
}
public class B {
private String msg1;
private String msg2;
private String msg3;
// getters and setters ...
}
.
Write a testclass andcheck theoutput
<bean id="a" abstract=“true”>
<property name="msg1" value="Tiger runs" />
<property name="msg2" value="Tiger eats" />
</bean>
Pushan Bhattacharya
Bean Reference (wiring)
Through setter or constructor injection we can refer to
another bean which has its own separate definition.
24
public class Person{
// ...
}
public class Location{
private String city;
public Location (String c){
this.city = c;
}
// ...
}
public class A {
private String msg;
private Person owner;
private Location address;
// getters and setters ...
}
<bean id="person"
class="Person" /> <bean id="location"
class="Location">
<constructor-arg
value="Kolkata"
type="java.lang.String" />
</bean>
<bean id="a" class="A">
<property name="msg" value="hello"/>
<property name="owner" ref="person"/>
<property name="address">
<ref bean="location" />
</property>
</bean>
Pushan Bhattacharya
Circular Dependency
25
Bean A Bean B
public class A {
private B b;
public A (B b) {
this.b = b;
}
}
public class B {
private A a;
public B (A a) {
this.a = a;
}
}
<bean id=“a” class=“A”>
<constructor-arg ref=“b” />
</bean>
<bean id=“b” class=“B”>
<constructor-arg ref=“a” />
</bean>
Pushan Bhattacharya
Inner Bean
Inner bean is also a bean reference.
A bean defined within another bean.
The inner bean is fully local to the outer bean.
The inner bean has prototype scope.
26
<bean id=“a” class=“A”>
<property name=“address”>
<bean class=“Location”>
<property name=“city” value=“Kolkata”/>
<property name=“zip” value=“700006”/>
</bean>
</property>
</bean>
public class A {
private Location address;
// getters and setters …
}
public class Location {
private String city, zip;
// getters and setters …
}
Pushan Bhattacharya
Injecting Collection
27
Tag Name
Inner Tag
Name
Java Collection
Type
Specification
<list> <value> java.util.List<E>
Allows duplicate
entries
<map> <entry> java.util.Map<K, V>
Key-Value pair of
any object type
<set> <value> java.util.Set<E>
Does not allow
duplicate entries
<props> <prop> java.util.Properties
Key-Value pair of
type ‘String’
Pushan Bhattacharya
So, lets inject some collection then …
28
<bean id=“animalCollection" class=“AnimalCollection">
<property name=“animalList">
<list>
<value>Tiger</value>
<value>Lion</value>
<value>Tiger</value>
</list>
</property>
<property name=“animalSet">
<set>
<value>Lion</value>
<value>Tiger</value>
<value>Lion</value>
</set>
</property>
<property name="animalMap">
<map>
<entry key="1" value=“Tiger"/>
<entry key="2" value=“Lion"/>
<entry key="3" value=“Tiger"/>
</map>
</property>
<property name="animalProp">
<props>
<prop key="one">Lion</prop>
<prop key="two">Tiger</prop>
<prop key="three">Lion</prop>
</props>
</property>
</bean>
public class AnimalCollection {
List<String> animalList;
Set<String> animalSet;
Map<String, String> animalMap;
Properties animalProp;
// getters and setters ...
}
public class MainClass {
public static void main(String… args) {
ApplicationContext ctx = new
ClassPathXmlApplicationContext(“wildLife.xml”);
AnimalCollection aC =(AnimalCollection)
ctx.getBean("animalCollection");
System.out.println(“animalList :” + aC.getAnimalList());
System.out.println(“animalSet:” + aC.getAnimalSet());
System.out.println(“animalMap:” + aC.getAnimalMap());
System.out.println(“animalProp:” + aC.getAnimalProp());
}
}
animalList :[Tiger, Lion, Tiger]
animalSet :[Lion, Tiger]
animalMap :{1=Tiger, 2=Lion, 3=Tiger}
animalProp :{one=Lion, two=Tiger, three=Lion}
Bean
definition
for DI
Bean
Test class
Output
Pushan Bhattacharya
Constructor v/s Setter Injection
Setter injection gets preference over constructor
injection when both are specified
Constructor injection cannot partially initialize values
Circular dependency can be achieved by setter
injection
Security is lesser in setter injection as it can be
overridden
Constructor injection fully ensures dependency
injection but setter injection does not
Setter injection is more readable
29
Pushan Bhattacharya
Bean Properties
30
Tag Name Description Example
id Unique Id <bean id=“person” … />
name Unique Name <bean name=“lion” … />
class Fully qualified Java class name <bean class=“a.b.C” … />
scope Bean object type <bean scope=“singleton” … />
constructor-arg Constructor injection <constructor-arg value=“a” />
property Setter injection <property name=“a” … />
autowire Automatic Bean referencing <bean autowire=“byName” … />
lazy-init Create a bean lazily (at its first request) <bean lazy-init=“true” … />
init-method
A callback method just after bean
creation
<bean init-method=“log” … />
destroy-method A callback just before bean destruction <bean destroy-method=“log” … />
Pushan Bhattacharya
Bean Life Cycle Callbacks
31
org.springframework.beans.factory.InitializingBean
void afterPropertiesSet () throws Exception;
public class MyBean implements
InitializingBean {
public void afterPropertiesSet () {
// Initialization work
}
}
<bean id=“myBean"
class=“MyBean" init-method="init"/>
public class MyBean {
public void init () {
// Initialization work
}
}
org.springframework.beans.factory.DisposableBean
void destroy () throws Exception;
public class MyBean implements
DisposableBean {
public void destroy () {
// Destruction work
}
}
<bean id=“myBean"
class=“MyBean" destroy-method=“des"/>
public class MyBean {
public void des () {
// Destruction work
}
}
Pushan Bhattacharya
Beans Auto-Wiring
32
Mode Description Example
no No auto wiring of beans Default
byName Auto wire beans by property name <bean autowire=“byName” … />
byType Auto wire beans by property type <bean autowire=“byType” … />
constructor Auto wire beans by constructor <bean autowire=“constructor” … />
autodetect First try by constructor, then by type <bean autowire=“autodetect” … />
Spring container can auto wire beans
In this case, there is no need to specify <property/> and/or
<constructor-arg/> tags
It decreases the amount of xml configuration
Pushan Bhattacharya
Removed
in Spring
3.0
Auto wire by Name
33
public class Person {
// ...
}
public class Location {
private String city;
public Location (String city) {
this.city = city;
}
// ...
}
public class A {
private String msg;
private Person person;
private Location location;
// getters and setters ...
}
<bean id="person"
class="Person" />
<bean id="location"
class="Location">
<constructor-arg value="Kolkata"
type="java.lang.String" />
</bean>
<bean id="a" class="A“ autowire=“byName”>
<property name="msg" value="hello" />
</bean>
Pushan Bhattacharya
Auto wire by Type
34
public class Person {
// ...
}
public class Location {
private String city;
public Location (String city) {
this.city = city;
}
// ...
}
public class A {
private String msg;
private Person owner;
private Location address;
// getters and setters ...
}
<bean id="person"
class="Person" />
<bean id="location"
class="Location">
<constructor-arg value="Kolkata"
type="java.lang.String" />
</bean>
<bean id="a" class="A“ autowire=“byType”>
<property name="msg" value="hello" />
</bean>
Pushan Bhattacharya
<!-- The below bean definition will destroy
the uniqueness of beans byType, hence
Spring will give exception. -->
<bean id=“person2" class=“Person”/>
Auto wire by Constructor
35
public class Person {
// ...
}
public class Location {
private String city;
public Location (String city) {
this.city = city;
}
// ...
}
public class A {
private String msg;
private Person owner;
private Location address;
public A (String m, Person o, Location a){
…
}
}
<bean id="person"
class="Person" />
<bean id="location"
class="Location">
<constructor-arg value="Kolkata"
type="java.lang.String" />
</bean>
<bean id="a" class="A“ autowire=“constructor”>
<property name="msg" value="hello" />
</bean>
Pushan Bhattacharya
Spring Auto-wiring Bottleneck
36
Disadvantage Description
Overriding beans configuration
If the bean configuration is specified explicitly then it overrides
the bean auto wiring configuration
Unable to wire primitive types
Auto wiring is applicable only for beans and not for simple
properties like primitives, String etc.
Auto wiring has confusing nature
Explicit wiring or manual wiring of beans is easier to
understand than auto wiring. It is preferred to use explicit
wiring if possible.
Partial wiring is not possible
Auto wiring will always try to wire all the beans through setter
or constructor. It cannot be used for partial wiring.
Spring auto wiring has certain disadvantages or limitations,
given below.
Pushan Bhattacharya
@Spring (annotation = start)
Evolved in Spring 2.0 (@Required).
Developed and became famous from Spring 2.5
“Old wine in new bottle” - an alternative of the xml
configuration for bean wiring
Not enabled by default (need explicit enabling)
XML overrides annotation for bean configuration
Sometimes gets treated as an anti-pattern since change
of annotation configuration needs compilation of code
IDE support
37
Pushan Bhattacharya
Enabling Spring Annotation
38
<?xml version="1.0" encoding="UTF-8“ ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd“ >
<context:annotation-config/>
<!--
<bean ... />
<bean ... />
.
.
.
<bean ... />
-->
</beans>
Pushan Bhattacharya
@Required
39
• Applicable to only setter methods. • Values by name.
• Strict checking.
public class Boy {
private String name;
private int age;
@Required
public void setName(String name){
this.name = name;
}
@Required
public void setAge(int age){
this.age = age;
}
// getters ...
}
<bean id=“boy” class=“Boy”>
<property name=“name” value=“Rony”/>
<property name=“age” value=“10”/>
</bean>
<bean id=“boy” class=“Boy”>
<property name=“name” value=“Rony”/>
</bean>
Property 'age' is required for bean
'boy'
Pushan Bhattacharya
@Autowired
40
• Applicable to methods, fields and
constructors
• Wiring by type.
• ‘required’ attribute
public class Boy {
private String name;
private int age;
// getters and setters ...
}
<bean id=“boy” class=“Boy”>
<property name=“name” value=“Rony”/>
<property name=“age” value=“10”/>
</bean>
public class College {
private String collegeId;
@Autowired
private Boy student;
public void setCollegeId(String cI){
this.collegeId = cI;
}
// getters ...
}
<bean id=“college” class=“College”>
<property name=“collegeId” value=“1A”/>
</bean>
public class College {
private String collegeId;
@Autowired(required=false)
private Boy student;
// ...
}
No setter
needed for
autowiring
on field
‘student’
auto wiring
becomes
optional
Pushan Bhattacharya
@Qualifier
41
• Solution to @Autowired for type ambiguity
public class Boy {
private String name;
private int age;
// getters and setters ...
}
public class College {
private String collegeId;
@Autowired
private Boy student;
public void setCollegeId(String cI){
this.collegeId = cI;
}
// getters ...
}
<bean id=“boy1” class=“Boy”>
<qualifier value=“rony”/>
<property name=“name” value=“Rony”/>
<property name=“age” value=“10”/>
</bean>
<bean id=“college” class=“College”>
<property name=“collegeId” value=“1A”/>
</bean>
<bean id=“boy2” class=“Boy”>
<qualifier value=“tony”/>
<property name=“name” value=“Tony”/>
<property name=“age” value=“8”/>
</bean>
@Qualifier(value=“tony”)
Qualifier
value
• If <qualifier/> is not configured, then searches
with bean id/name. But if specified, it will
always search with qualifier only.
Pushan Bhattacharya
@Resource, @PostConstruct, @PreDestroy
 @PostConstruct is an alternative of the init-method.
 @PreDestroy is an alternative of the destroy-method.
 @Resource(name=“<beanName>”) is used for auto wiring by name.
 @Resource can be applied in field, argument and methods.
 If no ‘name’ attribute is specified in @Resource, then the name is derived from
the field, setter method etc.
42
<bean id=“boy1” class=“Boy”>
<property name=“name” value=“Rony”/>
<property name=“age” value=“10”/>
</bean>
<bean id=“college” class=“College”>
<property name=“collegeId” value=“1A”/>
</bean>
<bean id=“boy2” class=“Boy”>
<property name=“name” value=“Tony”/>
<property name=“age” value=“8”/>
</bean>
public class College {
private String collegeId;
@Resource(name=“boy1”)
private Boy student;
// getters and setters ...
}
Pushan Bhattacharya
@Configuration & @Bean (Part I)
43
@Configuration
public class AnimalConfig{
@Bean
public Lion lion(){
return new Lion();
}
@Bean
public Tiger tiger(){
Tiger t = new Tiger();
t.doInit();
return t;
}
}
<bean id=“lion” class=“Lion” />
<bean id=“tiger” class=“Tiger”
init-method=“doInit” />
public class MainTest{
public static void main(String[] a){
ApplicationContext aC = new
AnnotationConfigApplicationContext(An
imalConfig.class);
Tiger t = aC.getBean(Tiger.class);
Lion l = aC.getBean(Lion.class);
// ...
}
}
Pushan Bhattacharya
@Configuration & @Bean (Part II)
44
@Configuration
public class LionConfig{
@Bean(destroyMethod=“clear”)
public Lion lion(){
return new Lion();
}
}
@Configuration
public class TigerConfig{
@Bean(initMethod=“doInit”)
public Tiger tiger(){
return new Tiger();
}
}
<bean id=“lion” class=“Lion”
destroy-method=“clear” />
<bean id=“tiger” class=“Tiger”
init-method=“doInit” />
public class MainTest{
public static void main(String[] a){
ApplicationContext aC = new
AnnotationConfigApplicationContext();
aC.register(LionConfig.class,
TigerConfig.class);
aC.refresh();
// ...
}
}
Pushan Bhattacharya
@Configuration & @Bean (Part III)
45
Pushan Bhattacharya
@Configuration
public class TigerConfig{
@Bean
public Tiger tiger(){
return new Tiger();
}
}
@Configuration
@Import(TigerConfig.class)
public class LionConfig{
@Bean
public Lion lion(){
return new Lion();
}
}
@Configuration
public class TigerConfig{
@Bean(name=“cat”)
@Scope(“prototype”)
public Tiger tiger(){
return new Tiger();
}
}
<bean id=“cat”
class=“Tiger”
scope=“prototype” />
Try Yourself
Are ‘Dependency Injection’ and ‘Inversion of Control’
same? Give reason for the answer.
How to achieve circular dependency via both setter and
constructor injection?
How to declare the <property> of the bean together with
the bean definition in a single line?
Why does an inner bean have the default scope as
‘prototype’?
46
Pushan Bhattacharya
Helping Resources
Spring source documentation
(http://www.springsource.org/documentation)
Tutorials Point tutorial
(http://www.tutorialspoint.com/spring)
Mkyong tutorial
(http://www.mkyong.com/tutorials/spring-
tutorials)
DZone (http://java.dzone.com/articles/case-spring-
inner-beans)
47
Pushan Bhattacharya
Please Review and Comment
48
- Pushan
Bhattacharya
Pushan Bhattacharya

More Related Content

What's hot

Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
07.pallav
 
Spring boot
Spring bootSpring boot
Spring boot
Bhagwat Kumar
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
Naphachara Rattanawilai
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
elliando dias
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
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 Boot
Spring BootSpring Boot
Spring Boot
HongSeong Jeon
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
Josué Neis
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
John Slick
 
Spring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaSpring Boot Interview Questions | Edureka
Spring Boot Interview Questions | Edureka
Edureka!
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jaran Flaath
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
VMware Tanzu
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
Sandeep Chawla
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
Spring boot
Spring bootSpring boot
Spring boot
Pradeep Shanmugam
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
nomykk
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
Muthuselvam RS
 

What's hot (20)

Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Spring boot
Spring bootSpring boot
Spring boot
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
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 Boot
Spring BootSpring Boot
Spring Boot
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Spring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaSpring Boot Interview Questions | Edureka
Spring Boot Interview Questions | Edureka
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 

Viewers also liked

Core Spring Education
Core Spring EducationCore Spring Education
Core Spring Education
AI Leadership Institute
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
Funnelll
 
Maven Presentation - SureFire vs FailSafe
Maven Presentation - SureFire vs FailSafeMaven Presentation - SureFire vs FailSafe
Maven Presentation - SureFire vs FailSafe
Holasz Kati
 
Apache maven, a software project management tool
Apache maven, a software project management toolApache maven, a software project management tool
Apache maven, a software project management tool
Renato Primavera
 
An introduction to maven gradle and sbt
An introduction to maven gradle and sbtAn introduction to maven gradle and sbt
An introduction to maven gradle and sbt
Fabio Fumarola
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
NexThoughts Technologies
 
Presentation Spring, Spring MVC
Presentation Spring, Spring MVCPresentation Spring, Spring MVC
Presentation Spring, Spring MVC
Nathaniel Richand
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Serhat Can
 
Spring framework 5: New Core and Reactive features
Spring framework 5: New Core and Reactive featuresSpring framework 5: New Core and Reactive features
Spring framework 5: New Core and Reactive features
Aliaksei Zhynhiarouski
 

Viewers also liked (9)

Core Spring Education
Core Spring EducationCore Spring Education
Core Spring Education
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Maven Presentation - SureFire vs FailSafe
Maven Presentation - SureFire vs FailSafeMaven Presentation - SureFire vs FailSafe
Maven Presentation - SureFire vs FailSafe
 
Apache maven, a software project management tool
Apache maven, a software project management toolApache maven, a software project management tool
Apache maven, a software project management tool
 
An introduction to maven gradle and sbt
An introduction to maven gradle and sbtAn introduction to maven gradle and sbt
An introduction to maven gradle and sbt
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Presentation Spring, Spring MVC
Presentation Spring, Spring MVCPresentation Spring, Spring MVC
Presentation Spring, Spring MVC
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring framework 5: New Core and Reactive features
Spring framework 5: New Core and Reactive featuresSpring framework 5: New Core and Reactive features
Spring framework 5: New Core and Reactive features
 

Similar to Spring Core

Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
Washington Botelho
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
Collaboration Technologies
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
Raveendra R
 
Spring 3.0 dependancy injection
Spring 3.0 dependancy injectionSpring 3.0 dependancy injection
Spring 3.0 dependancy injection
Rajiv Gupta
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"
IT Event
 
Python mu Java mı?
Python mu Java mı?Python mu Java mı?
Python mu Java mı?
aerkanc
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Gandhi Ravi
 
Spring FrameWork Tutorials Java Language
Spring FrameWork Tutorials Java Language Spring FrameWork Tutorials Java Language
Spring FrameWork Tutorials Java Language
Mahika Tutorials
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
VMware Tanzu
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Subramanyan Murali
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
C.T.Co
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
Alexey Buzdin
 
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
Peter Antman
 
Java2
Java2Java2
Python mu Java mı?
Python mu Java mı?Python mu Java mı?
Python mu Java mı?
aerkanc
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
Joshua Long
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
Ignacio Coloma
 
Spring
SpringSpring
Spring
s4al_com
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
s4al_com
 
Spring boot
Spring boot Spring boot
Spring boot
Vinay Prajapati
 

Similar to Spring Core (20)

Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Spring 3.0 dependancy injection
Spring 3.0 dependancy injectionSpring 3.0 dependancy injection
Spring 3.0 dependancy injection
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"
 
Python mu Java mı?
Python mu Java mı?Python mu Java mı?
Python mu Java mı?
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Spring FrameWork Tutorials Java Language
Spring FrameWork Tutorials Java Language Spring FrameWork Tutorials Java Language
Spring FrameWork Tutorials Java Language
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
 
Java2
Java2Java2
Java2
 
Python mu Java mı?
Python mu Java mı?Python mu Java mı?
Python mu Java mı?
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Spring
SpringSpring
Spring
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 
Spring boot
Spring boot Spring boot
Spring boot
 

Recently uploaded

7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
Enterprise Wired
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Erasmo Purificato
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Chris Swan
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
amitchopra0215
 
K2G - Insurtech Innovation EMEA Award 2024
K2G - Insurtech Innovation EMEA Award 2024K2G - Insurtech Innovation EMEA Award 2024
K2G - Insurtech Innovation EMEA Award 2024
The Digital Insurer
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
jackson110191
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
huseindihon
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Mydbops
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
Vijayananda Mohire
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
Larry Smarr
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024
The Digital Insurer
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
Matthew Sinclair
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
ArgaBisma
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
shanthidl1
 
AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)
apoorva2579
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
Safe Software
 

Recently uploaded (20)

7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
 
K2G - Insurtech Innovation EMEA Award 2024
K2G - Insurtech Innovation EMEA Award 2024K2G - Insurtech Innovation EMEA Award 2024
K2G - Insurtech Innovation EMEA Award 2024
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
 
AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)AC Atlassian Coimbatore Session Slides( 22/06/2024)
AC Atlassian Coimbatore Session Slides( 22/06/2024)
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
 

Spring Core

  • 1. BY PUSHAN BHATTACHARYA Its time for 1 Pushan Bhattacharya
  • 2. Agenda – what to do in this Spring Dependency Injection Overview of Spring Framework Various injections and their usages in detail Bean scope Bean wiring Inner bean Bean properties Bean life cycle Bean auto wiring Spring Annotation 2 Pushan Bhattacharya
  • 3. High Dependency = High Responsibility public class Tiger { public void eat() { System.out.println(“Do not disturb”); } } public class MainClass { public static void main(String… args) { Tiger t = new Tiger(); t.eat(); } } 3 o Requirement: Change Tiger to Lion. o Me: Urggghhh. Too many changes. 1. Standalone Lion class 2. Change the object declaration to Lion 3. Change the reference 4. Compile again 5. Test Pushan Bhattacharya
  • 4. A bit less dependency public interface Animal { void eat(); } public class Tiger implements Animal { @Override public void eat() { System.out.println(“Do not disturb”); } } public class MainClass { public static void main(String… args) { Animal a = new Tiger(); a.eat(); } } 4 o Requirement: Change Tiger to Lion. o Me: Ufff. Again some changes. 1. Lion implements Animal 2. Change the object declaration to Lion 3. Change the reference 4. Compile again 5. Test Pushan Bhattacharya
  • 5. Dependency Injection public interface Animal { void eat(); } public class Tiger implements Animal { @Override public void eat() { System.out.println(“Do not disturb”); } } public class MainClass { public static void main(String… args) { ApplicationContext aC = new ClassPathXmlApplicationContext(“wildLife.xml”); Animal a = (Animal) aC.getBean(“animal”); a.eat(); } } wildLife.xml <bean id = “animal” class = “Tiger” /> 5 o Requirement: Change Tiger to Lion. o Me: Ok. Small change. 1. Lion implements Animal 2. Change bean class to Lion 3. Change the reference 4. Compile again 5. Test Pushan Bhattacharya
  • 6. So what is Spring? IoC container Lightweight framework Fully modularized (High decoupling) Considered an alternative / replacement for the Enterprise JavaBean (EJB) model Flexible  Programmers decide how to program Not exclusive to Java (e.g. .NET) Solutions to typical coding busywork  JDBC  LDAP  Web Services 6 Pushan Bhattacharya
  • 7. What Spring offers? Dependency Injection (DI)  DI is implemented through IoC (Inversion of Control) Aspect Oriented Programming  Runtime injection-based Portable Service Abstractions  The rest of spring  ORM, DAO, Web MVC, Web, etc.  Allows access to these without knowing how they actually work Easily testable 7 Pushan Bhattacharya
  • 8. What is a bean? A Bean is a class that has only state but no behavior A Bean must contain a no-argument constructor A Bean should be serialized 8 Class Bean Pushan Bhattacharya
  • 9. Spring Framework Architecture 9 Pushan Bhattacharya SPRING CORE CONTAINER T E S T BeansCore Context Expression Language DATA ACCESS INTEGRATION Spring ORM Spring DAO WEB LAYER Spring WEB Services SPRING WEB MVC FRAMEWORK SPRING AOP
  • 10. Spring Bean Configuration 10 Pushan Bhattacharya <?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd“ > <bean id = “animal” class = “com.pushan.spring.beans.Tiger“ > <property name = “msg” value = “Eating now“ /> </bean> <!-- . . . --> </beans>
  • 11. Spring IoC Container 11 Pushan Bhattacharya Bean / POJO / Application Class Bean Configuration Metadata Completely Configured Application Ready to Use Spring IoC Container Registered Input Output 1 2 3
  • 12. Spring IoC Container contd… 12 BeanFactory ApplicationContext The simplest factory, mainly for DI The advanced and more complex factory Used when resources are limited, e.g., mobile, applets etc. Used elsewhere and has the below features, 1> Enterprise aware functions 2> Publish application events to listeners 3> Wire and dispose beans on request org.springframework.beans.factory.BeanFactory org.springframework.context.ApplicationContext XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource(“wildLife.xml")); ApplicationContext aC = new ClassPathXmlApplicationContext(“wildLi fe.xml”); Pushan Bhattacharya
  • 13. Injection Methods Setter Injection  Pass dependencies in via property setters (e.g., Spring) Constructor Injection  Pass dependencies in via constructor (e.g., Spring) Interface Injection  Pass dependencies in via interfaces (e.g., Avalon) 13 public class MainClass { public static void main(String… args) { ApplicationContext aC = new ClassPathXmlApplicationContext(“wild Life.xml”); Animal a = (Animal) aC.getBean(“animal”); a.eat(); wildLife.xml <bean id = “animal” class = “Tiger” /> Pushan Bhattacharya
  • 14. Setter Injection In the <bean>, Specify <property> tag. 14 public class College { private String collegeId; private int totalStudents; public String getCollegeId() { return collegeId; } public void setCollegeId(String collegeId) { this.collegeId = collegeId; } public int getTotalStudents() { return totalStudents; } public void setTotalStudents(int totalStudents) { this.totalStudents = totalStudents; } public class MyClass { private static final String MY_COLLEGE = "myCollege"; public static void main(String... args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("springConfig.xml" College col = (College) ctx.getBean(MY_COLLEGE); System.out.println("College Id: " + col.getCollegeId()); System.out.println("Total Students: " + col.getTotalStudents()); } } <bean id="myCollege" class="com.pushan.study.spring.beans.College" > <property name="collegeId" value="123Abc"/> <property name="totalStudents" Pushan Bhattacharya
  • 15. Constructor Injection 15 In the <bean>, Specify <constructor-arg> public class College { private String collegeId; private int totalStudents; public void College (int tS, String cI) { this.totalStudents = tS; this.collegeId = cI; } public String getCollegeId(){ return collegeId; } public int getTotalStudents() { return totalStudents; public class MyClass { private static final String MY_COLLEGE = "myCollege"; public static void main(String... args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("springConfig.xml "); College col = (College) ctx.getBean(MY_COLLEGE); System.out.println("College Id: " + col.getCollegeId()); System.out.println("Total Students: " + col.getTotalStudents()); } } <bean id="myCollege" class="com.pushan.study.spring.beans.College" > <constructor-arg type=“int” value=“500”/> <constructor-arg type=“java.lang.String” value=“123Abc”/> Pushan Bhattacharya
  • 16. Constructor Injection Illustrated The ‘value’ attribute is mandatory and rest are optional, e.g., ‘type’ Constructor Injection can automatically cast the value to the desired ‘known’ type By default the ‘type’ of the ‘value’ is ‘java.lang.String’ (if not specified explicitly) Constructor injection does not interpret ordering of the arguments specified 16 Pushan Bhattacharya
  • 17. Constructor Injection Ambiguity 1 17 <bean id="myCollege" class="com.pushan.College"> <constructor-arg value=“500”/> <constructor-arg value=“123Abc”/> </bean> public class College { private String collegeId; private int totalStudents; private String collegeAdd; public College (int totalStudents, String collegeId){ this.totalStudents = totalStudents; this.collegeId = collegeId; } public College (String collegeAdd, String collegeId){ this.collegeAdd = collegeAdd; this.collegeId = collegeId; } } Which constructor will be called? Pushan Bhattacharya
  • 18. Constructor Injection Ambiguity 1 Solution 18 <bean id="myCollege" class="com.pushan.College"> <constructor-arg value=“500” type=“int”/> <constructor-arg value=“123Abc” type=“java.lang.String”/> </bean> The ‘type’ of the value is specified public class College { private String collegeId; private int totalStudents; private String collegeAdd; public College (int totalStudents, String collegeId){ this.totalStudents = totalStudents; this.collegeId = collegeId; } public College (String collegeAdd, String collegeId){ this.collegeAdd = collegeAdd; this.collegeId = collegeId; } } Pushan Bhattacharya
  • 19. Constructor Injection Ambiguity 2 19 <bean id="myCollege" class="com.pushan.College"> <constructor-arg value=“500” type=“int”/> <constructor-arg value=“123Abc” type=“java.lang.String”/> </bean> public class College { private String collegeId; private int totalStudents; private String collegeAdd; public College (int totalStudents, String collegeId){ this.totalStudents = totalStudents; this.collegeId = collegeId; } public College (String collegeAdd, int totalStudents){ this.totalStudents = totalStudents; this. collegeAdd = collegeAdd; } } Which constructor will be called? Pushan Bhattacharya
  • 20. Constructor Injection Ambiguity 2 Solution 20 The ‘index’ of the value is specified <bean id="myCollege" class="com.pushan.College"> <constructor-arg value=“500” type=“int” index=“0”/> <constructor-arg value=“123Abc” type=“java.lang.String” index=“1”/> </bean> public class College { private String collegeId; private int totalStudents; private String collegeAdd; public College (int totalStudents, String collegeId){ this.totalStudents = totalStudents; this.collegeId = collegeId; } public College (String collegeAdd, int totalStudents){ this.totalStudents = totalStudents; this. collegeAdd = collegeAdd; } } Pushan Bhattacharya
  • 21. Bean Scope 1 – Object Type (Part I) Pushan Bhattacharya 21 Bean Scope Description singleton Single instance of bean in every getBean() call [Default] prototype New instance of bean in every getBean() call request Single instance of bean per HTTP request session Single instance of bean per HTTP session global-session Single instance of bean per global HTTP session thread Single instance of bean per thread custom Customized scope Valid in the context of web-aware ApplicationContext Added in Spring 3.0 We will look into ‘singleton’ and ‘prototype’ scopes only
  • 22. Bean Scope 1 – Object Type (Part II) Mainly bean can be of two types, viz., 1. Singleton (e.g., <bean scope=“singleton” … />) 2. Prototype (e.g., <bean scope=“prototype” … />) A ‘singleton’ bean is created once in the Spring container. This ‘singleton’ bean is given every time when referred. It is garbage collected when the container shuts down. A ‘prototype’ bean means a new object in every request. It is garbage collected in the normal way, i.e., when there is no reference for this object. By default every bean is singleton if not specified explicitly. 22 Pushan Bhattacharya
  • 23. Bean Scope 2 - Inheritance 23 <bean id="a" class=“A” > <property name="msg1" value="Tiger runs" /> <property name="msg2" value="Tiger eats" /> </bean> <bean id="b" class="B" parent="a"> <property name="msg1" value="Lion runs" /> <property name="msg3" value="Lion sleeps" /> </bean> public class A { private String msg1; private String msg2; // getters and setters ... } public class B { private String msg1; private String msg2; private String msg3; // getters and setters ... } . Write a testclass andcheck theoutput <bean id="a" abstract=“true”> <property name="msg1" value="Tiger runs" /> <property name="msg2" value="Tiger eats" /> </bean> Pushan Bhattacharya
  • 24. Bean Reference (wiring) Through setter or constructor injection we can refer to another bean which has its own separate definition. 24 public class Person{ // ... } public class Location{ private String city; public Location (String c){ this.city = c; } // ... } public class A { private String msg; private Person owner; private Location address; // getters and setters ... } <bean id="person" class="Person" /> <bean id="location" class="Location"> <constructor-arg value="Kolkata" type="java.lang.String" /> </bean> <bean id="a" class="A"> <property name="msg" value="hello"/> <property name="owner" ref="person"/> <property name="address"> <ref bean="location" /> </property> </bean> Pushan Bhattacharya
  • 25. Circular Dependency 25 Bean A Bean B public class A { private B b; public A (B b) { this.b = b; } } public class B { private A a; public B (A a) { this.a = a; } } <bean id=“a” class=“A”> <constructor-arg ref=“b” /> </bean> <bean id=“b” class=“B”> <constructor-arg ref=“a” /> </bean> Pushan Bhattacharya
  • 26. Inner Bean Inner bean is also a bean reference. A bean defined within another bean. The inner bean is fully local to the outer bean. The inner bean has prototype scope. 26 <bean id=“a” class=“A”> <property name=“address”> <bean class=“Location”> <property name=“city” value=“Kolkata”/> <property name=“zip” value=“700006”/> </bean> </property> </bean> public class A { private Location address; // getters and setters … } public class Location { private String city, zip; // getters and setters … } Pushan Bhattacharya
  • 27. Injecting Collection 27 Tag Name Inner Tag Name Java Collection Type Specification <list> <value> java.util.List<E> Allows duplicate entries <map> <entry> java.util.Map<K, V> Key-Value pair of any object type <set> <value> java.util.Set<E> Does not allow duplicate entries <props> <prop> java.util.Properties Key-Value pair of type ‘String’ Pushan Bhattacharya
  • 28. So, lets inject some collection then … 28 <bean id=“animalCollection" class=“AnimalCollection"> <property name=“animalList"> <list> <value>Tiger</value> <value>Lion</value> <value>Tiger</value> </list> </property> <property name=“animalSet"> <set> <value>Lion</value> <value>Tiger</value> <value>Lion</value> </set> </property> <property name="animalMap"> <map> <entry key="1" value=“Tiger"/> <entry key="2" value=“Lion"/> <entry key="3" value=“Tiger"/> </map> </property> <property name="animalProp"> <props> <prop key="one">Lion</prop> <prop key="two">Tiger</prop> <prop key="three">Lion</prop> </props> </property> </bean> public class AnimalCollection { List<String> animalList; Set<String> animalSet; Map<String, String> animalMap; Properties animalProp; // getters and setters ... } public class MainClass { public static void main(String… args) { ApplicationContext ctx = new ClassPathXmlApplicationContext(“wildLife.xml”); AnimalCollection aC =(AnimalCollection) ctx.getBean("animalCollection"); System.out.println(“animalList :” + aC.getAnimalList()); System.out.println(“animalSet:” + aC.getAnimalSet()); System.out.println(“animalMap:” + aC.getAnimalMap()); System.out.println(“animalProp:” + aC.getAnimalProp()); } } animalList :[Tiger, Lion, Tiger] animalSet :[Lion, Tiger] animalMap :{1=Tiger, 2=Lion, 3=Tiger} animalProp :{one=Lion, two=Tiger, three=Lion} Bean definition for DI Bean Test class Output Pushan Bhattacharya
  • 29. Constructor v/s Setter Injection Setter injection gets preference over constructor injection when both are specified Constructor injection cannot partially initialize values Circular dependency can be achieved by setter injection Security is lesser in setter injection as it can be overridden Constructor injection fully ensures dependency injection but setter injection does not Setter injection is more readable 29 Pushan Bhattacharya
  • 30. Bean Properties 30 Tag Name Description Example id Unique Id <bean id=“person” … /> name Unique Name <bean name=“lion” … /> class Fully qualified Java class name <bean class=“a.b.C” … /> scope Bean object type <bean scope=“singleton” … /> constructor-arg Constructor injection <constructor-arg value=“a” /> property Setter injection <property name=“a” … /> autowire Automatic Bean referencing <bean autowire=“byName” … /> lazy-init Create a bean lazily (at its first request) <bean lazy-init=“true” … /> init-method A callback method just after bean creation <bean init-method=“log” … /> destroy-method A callback just before bean destruction <bean destroy-method=“log” … /> Pushan Bhattacharya
  • 31. Bean Life Cycle Callbacks 31 org.springframework.beans.factory.InitializingBean void afterPropertiesSet () throws Exception; public class MyBean implements InitializingBean { public void afterPropertiesSet () { // Initialization work } } <bean id=“myBean" class=“MyBean" init-method="init"/> public class MyBean { public void init () { // Initialization work } } org.springframework.beans.factory.DisposableBean void destroy () throws Exception; public class MyBean implements DisposableBean { public void destroy () { // Destruction work } } <bean id=“myBean" class=“MyBean" destroy-method=“des"/> public class MyBean { public void des () { // Destruction work } } Pushan Bhattacharya
  • 32. Beans Auto-Wiring 32 Mode Description Example no No auto wiring of beans Default byName Auto wire beans by property name <bean autowire=“byName” … /> byType Auto wire beans by property type <bean autowire=“byType” … /> constructor Auto wire beans by constructor <bean autowire=“constructor” … /> autodetect First try by constructor, then by type <bean autowire=“autodetect” … /> Spring container can auto wire beans In this case, there is no need to specify <property/> and/or <constructor-arg/> tags It decreases the amount of xml configuration Pushan Bhattacharya Removed in Spring 3.0
  • 33. Auto wire by Name 33 public class Person { // ... } public class Location { private String city; public Location (String city) { this.city = city; } // ... } public class A { private String msg; private Person person; private Location location; // getters and setters ... } <bean id="person" class="Person" /> <bean id="location" class="Location"> <constructor-arg value="Kolkata" type="java.lang.String" /> </bean> <bean id="a" class="A“ autowire=“byName”> <property name="msg" value="hello" /> </bean> Pushan Bhattacharya
  • 34. Auto wire by Type 34 public class Person { // ... } public class Location { private String city; public Location (String city) { this.city = city; } // ... } public class A { private String msg; private Person owner; private Location address; // getters and setters ... } <bean id="person" class="Person" /> <bean id="location" class="Location"> <constructor-arg value="Kolkata" type="java.lang.String" /> </bean> <bean id="a" class="A“ autowire=“byType”> <property name="msg" value="hello" /> </bean> Pushan Bhattacharya <!-- The below bean definition will destroy the uniqueness of beans byType, hence Spring will give exception. --> <bean id=“person2" class=“Person”/>
  • 35. Auto wire by Constructor 35 public class Person { // ... } public class Location { private String city; public Location (String city) { this.city = city; } // ... } public class A { private String msg; private Person owner; private Location address; public A (String m, Person o, Location a){ … } } <bean id="person" class="Person" /> <bean id="location" class="Location"> <constructor-arg value="Kolkata" type="java.lang.String" /> </bean> <bean id="a" class="A“ autowire=“constructor”> <property name="msg" value="hello" /> </bean> Pushan Bhattacharya
  • 36. Spring Auto-wiring Bottleneck 36 Disadvantage Description Overriding beans configuration If the bean configuration is specified explicitly then it overrides the bean auto wiring configuration Unable to wire primitive types Auto wiring is applicable only for beans and not for simple properties like primitives, String etc. Auto wiring has confusing nature Explicit wiring or manual wiring of beans is easier to understand than auto wiring. It is preferred to use explicit wiring if possible. Partial wiring is not possible Auto wiring will always try to wire all the beans through setter or constructor. It cannot be used for partial wiring. Spring auto wiring has certain disadvantages or limitations, given below. Pushan Bhattacharya
  • 37. @Spring (annotation = start) Evolved in Spring 2.0 (@Required). Developed and became famous from Spring 2.5 “Old wine in new bottle” - an alternative of the xml configuration for bean wiring Not enabled by default (need explicit enabling) XML overrides annotation for bean configuration Sometimes gets treated as an anti-pattern since change of annotation configuration needs compilation of code IDE support 37 Pushan Bhattacharya
  • 38. Enabling Spring Annotation 38 <?xml version="1.0" encoding="UTF-8“ ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd“ > <context:annotation-config/> <!-- <bean ... /> <bean ... /> . . . <bean ... /> --> </beans> Pushan Bhattacharya
  • 39. @Required 39 • Applicable to only setter methods. • Values by name. • Strict checking. public class Boy { private String name; private int age; @Required public void setName(String name){ this.name = name; } @Required public void setAge(int age){ this.age = age; } // getters ... } <bean id=“boy” class=“Boy”> <property name=“name” value=“Rony”/> <property name=“age” value=“10”/> </bean> <bean id=“boy” class=“Boy”> <property name=“name” value=“Rony”/> </bean> Property 'age' is required for bean 'boy' Pushan Bhattacharya
  • 40. @Autowired 40 • Applicable to methods, fields and constructors • Wiring by type. • ‘required’ attribute public class Boy { private String name; private int age; // getters and setters ... } <bean id=“boy” class=“Boy”> <property name=“name” value=“Rony”/> <property name=“age” value=“10”/> </bean> public class College { private String collegeId; @Autowired private Boy student; public void setCollegeId(String cI){ this.collegeId = cI; } // getters ... } <bean id=“college” class=“College”> <property name=“collegeId” value=“1A”/> </bean> public class College { private String collegeId; @Autowired(required=false) private Boy student; // ... } No setter needed for autowiring on field ‘student’ auto wiring becomes optional Pushan Bhattacharya
  • 41. @Qualifier 41 • Solution to @Autowired for type ambiguity public class Boy { private String name; private int age; // getters and setters ... } public class College { private String collegeId; @Autowired private Boy student; public void setCollegeId(String cI){ this.collegeId = cI; } // getters ... } <bean id=“boy1” class=“Boy”> <qualifier value=“rony”/> <property name=“name” value=“Rony”/> <property name=“age” value=“10”/> </bean> <bean id=“college” class=“College”> <property name=“collegeId” value=“1A”/> </bean> <bean id=“boy2” class=“Boy”> <qualifier value=“tony”/> <property name=“name” value=“Tony”/> <property name=“age” value=“8”/> </bean> @Qualifier(value=“tony”) Qualifier value • If <qualifier/> is not configured, then searches with bean id/name. But if specified, it will always search with qualifier only. Pushan Bhattacharya
  • 42. @Resource, @PostConstruct, @PreDestroy  @PostConstruct is an alternative of the init-method.  @PreDestroy is an alternative of the destroy-method.  @Resource(name=“<beanName>”) is used for auto wiring by name.  @Resource can be applied in field, argument and methods.  If no ‘name’ attribute is specified in @Resource, then the name is derived from the field, setter method etc. 42 <bean id=“boy1” class=“Boy”> <property name=“name” value=“Rony”/> <property name=“age” value=“10”/> </bean> <bean id=“college” class=“College”> <property name=“collegeId” value=“1A”/> </bean> <bean id=“boy2” class=“Boy”> <property name=“name” value=“Tony”/> <property name=“age” value=“8”/> </bean> public class College { private String collegeId; @Resource(name=“boy1”) private Boy student; // getters and setters ... } Pushan Bhattacharya
  • 43. @Configuration & @Bean (Part I) 43 @Configuration public class AnimalConfig{ @Bean public Lion lion(){ return new Lion(); } @Bean public Tiger tiger(){ Tiger t = new Tiger(); t.doInit(); return t; } } <bean id=“lion” class=“Lion” /> <bean id=“tiger” class=“Tiger” init-method=“doInit” /> public class MainTest{ public static void main(String[] a){ ApplicationContext aC = new AnnotationConfigApplicationContext(An imalConfig.class); Tiger t = aC.getBean(Tiger.class); Lion l = aC.getBean(Lion.class); // ... } } Pushan Bhattacharya
  • 44. @Configuration & @Bean (Part II) 44 @Configuration public class LionConfig{ @Bean(destroyMethod=“clear”) public Lion lion(){ return new Lion(); } } @Configuration public class TigerConfig{ @Bean(initMethod=“doInit”) public Tiger tiger(){ return new Tiger(); } } <bean id=“lion” class=“Lion” destroy-method=“clear” /> <bean id=“tiger” class=“Tiger” init-method=“doInit” /> public class MainTest{ public static void main(String[] a){ ApplicationContext aC = new AnnotationConfigApplicationContext(); aC.register(LionConfig.class, TigerConfig.class); aC.refresh(); // ... } } Pushan Bhattacharya
  • 45. @Configuration & @Bean (Part III) 45 Pushan Bhattacharya @Configuration public class TigerConfig{ @Bean public Tiger tiger(){ return new Tiger(); } } @Configuration @Import(TigerConfig.class) public class LionConfig{ @Bean public Lion lion(){ return new Lion(); } } @Configuration public class TigerConfig{ @Bean(name=“cat”) @Scope(“prototype”) public Tiger tiger(){ return new Tiger(); } } <bean id=“cat” class=“Tiger” scope=“prototype” />
  • 46. Try Yourself Are ‘Dependency Injection’ and ‘Inversion of Control’ same? Give reason for the answer. How to achieve circular dependency via both setter and constructor injection? How to declare the <property> of the bean together with the bean definition in a single line? Why does an inner bean have the default scope as ‘prototype’? 46 Pushan Bhattacharya
  • 47. Helping Resources Spring source documentation (http://www.springsource.org/documentation) Tutorials Point tutorial (http://www.tutorialspoint.com/spring) Mkyong tutorial (http://www.mkyong.com/tutorials/spring- tutorials) DZone (http://java.dzone.com/articles/case-spring- inner-beans) 47 Pushan Bhattacharya
  • 48. Please Review and Comment 48 - Pushan Bhattacharya Pushan Bhattacharya