SlideShare a Scribd company logo
Java Spring Training
Spring Continued…
Page 1Classification: Restricted
Agenda
• Auto-wiring
• Annotations based configuration
• Java based configuration
Java & JEE Training
Autowiring
Page 3Classification: Restricted
Autowiring Beans
• The Spring container can autowire relationships between collaborating
beans without using <constructor-arg> and <property> elements
• This helps cut down on the amount of XML configuration you write for a
big Spring based application.
Page 4Classification: Restricted
Autowiring Modes
Mode Description
no This is default setting which means no autowiring and you should use explicit
bean reference for wiring. You have nothing to do special for this wiring.
byName Autowiring by property name. Spring container looks at the properties of the
beans on which autowire attribute is set to byName in the XML configuration
file. It then tries to match and wire its properties with the beans defined by
the same names in the configuration file.
byType Autowiring by property datatype. Spring container looks at the properties of
the beans on which autowire attribute is set to byType in the XML
configuration file. It then tries to match and wire a property if its type matches
with exactly one of the beans name in configuration file. If more than one such
beans exists, a fatal exception is thrown.
constructor Similar to byType, but type applies to constructor arguments. If there is not
exactly one bean of the constructor argument type in the container, a fatal
error is raised.
autodetect Spring first tries to wire using autowire by constructor, if it does not work,
Spring tries to autowire by byType.
Page 5Classification: Restricted
Autowiring - byName
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="demo.TextEditor">
<property name="spellChecker" ref="spellChecker" />
<property name="name" value="Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="demo.SpellChecker">
</bean>
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="demo.TextEditor" autowire="byName">
<property name="name" value="Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<!– SpellChecker spellchecker = new SpellChecker(); -->
<bean id="spellChecker" class="demo.SpellChecker">
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker2" class="demo.SpellChecker">
</bean>
Page 6Classification: Restricted
Autowiring - byType
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="demo.TextEditor">
<property name="spellChecker" ref="spellChecker" />
<property name="name" value="Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="demo.SpellChecker">
</bean>
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="demo.TextEditor" autowire="byType">
<property name="name" value="Generic Text Editor" />
</bean>
<!-- Definition for spellChecker bean -->
<bean id="SpellChecker" class="demo.SpellChecker">
</bean>
<!-- Definition for spellChecker bean; Only one bean definition allowed.-->
<bean id="SpellChecker1" class="demo.SpellChecker">
</bean>
Page 7Classification: Restricted
Autowiring - constructor
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="demo.TextEditor">
<constructor-arg ref="spellChecker" />
<constructor-arg value="Generic Text Editor"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="demo.SpellChecker">
</bean>
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="demo.TextEditor“ autowire="constructor">
<constructor-arg value="Generic Text Editor"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id="SpellChecker" class="demo.SpellChecker">
</bean>
Page 8Classification: Restricted
Exercise…
• Try autodetect mode.
Java & JEE Training
Annotation Based Configuration
Page 10Classification: Restricted
Annotation Based Configuration
• Starting Spring 2.5, instead of using XML to describe a bean wiring, you can
move the bean configuration into the component class itself by using
annotations on the relevant class, method, or field declaration.
• Annotation injection is performed before XML injection, thus the latter
configuration will override the former for properties wired through both
approaches.
Page 11Classification: Restricted
Switching on Annotation based configuration/wiring
• Not switched on by default.
• Enable it in the configuration xml file.
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>
Page 12Classification: Restricted
Switching on Annotation based configuration/wiring
• Once <context:annotation-config/> is configured, you can start annotating
your code to indicate that Spring should automatically wire values into
properties, methods, and constructors.
• Following significant annotations are used:
@Required
@Autowired
@Qualifier
Page 13Classification: Restricted
@Required Annotation
• applies to bean property setter methods and it indicates that the affected
bean property must be populated in XML configuration file at configuration
time
• otherwise the container throws a BeanInitializationException exception
public class Student {
private Integer age;
private String name;
@Required
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
@Required
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Page 14Classification: Restricted
@Autowired
• provides more fine-grained control over where and how autowiring should
be accomplished.
• The @Autowired annotation can be used to autowire bean on the setter
method just like @Required annotation, constructor, a property or
methods with arbitrary names and/or multiple arguments.
Page 15Classification: Restricted
@Autowired on setter methods
• Use @Autowired annotation on setter methods to get rid of the
<property> element in XML configuration file.
• When Spring finds an @Autowired annotation used with setter methods, it
tries to perform byType autowiring on the method.
//Student.java
private Address address;
@Autowired
public void setAddress( Address address){
this.address = address;
}
<context:annotation-config/>
<!-- Definition for student bean without constructor-arg -->
<bean id=“student" class=“demo.Student">
</bean>
<!-- Definition for address bean -->
<bean id=“address" class=“demo.address">
</bean>
Page 16Classification: Restricted
@Autowired on Constructors
• A constructor @Autowired annotation indicates that the constructor
should be autowired when creating the bean, even if no <constructor-arg>
elements are used while configuring the bean in XML file.
private SpellChecker spellChecker;
@Autowired
public TextEditor(SpellChecker spellChecker){
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
<context:annotation-config/>
<!-- Definition for textEditor bean without constructor-arg -->
<bean id="textEditor" class="demo.TextEditor">
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="demo.SpellChecker">
</bean>
Page 17Classification: Restricted
@Autowired(required=false)
• By default, the @Autowired annotation => the dependency is required
similar to @Required annotation.
• However, you can turn off the default behavior by using (required = false)
option with @Autowired.
public class Student {
private Integer age;
private String name;
@Autowired(required=false)
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
@Autowired
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Page 18Classification: Restricted
@Qualifier with @Autowired – remove confusion
public class Profile {
@Autowired
@Qualifier("student1")
private Student student;
public Profile(){
System.out.println("Inside Profile constructor." );
}
….
<context:annotation-config/>
<!-- Definition for profile bean -->
<bean id="profile" class="demo.Profile"> </bean>
<!-- Definition for student1 bean -->
<bean id="student1" class="demo.Student">
<property name="name" value="Zara" />
<property name="age" value="11"/>
</bean>
<!-- Definition for student2 bean -->
<bean id="student2" class="demo.Student">
<property name="name" value="Nuha" />
<property name="age" value="2"/>
</bean>
Java & JEE Training
Java Based Configuration
Page 20Classification: Restricted
Java based configuration using- @Configuration and @Bean
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
<beans>
<bean id="helloWorld" class=“demo.HelloWorld" />
</beans>
ApplicationContext ctx =
new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
Page 21Classification: Restricted
Java based configuration… Injecting bean dependency
import org.springframework.context.annotation.*;
@Configuration
public class AppConfig {
@Bean
public Foo foo() {
return new Foo(bar());
}
@Bean
public Bar bar() {
return new Bar();
}
}
?? Complete the exercise..
Page 22Classification: Restricted
Java based configuration - @Import
@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}
@Configuration
@Import(ConfigA.class)
public class ConfigB {
@Bean
public B a() {
return new A();
}
}
ApplicationContext ctx =
new AnnotationConfigApplicationContext(ConfigB.class);
Page 23Classification: Restricted
Specifying Bean Scope
@Configuration
public class AppConfig {
@Bean
@Scope("prototype")
public Foo foo() {
return new Foo();
}
}
Page 24Classification: Restricted
Topics to be covered in next session
• Spring AOP
• What is AOP
• AOP Terminologies
• AOP Implementations
Page 25Classification: Restricted
Thank you!

More Related Content

What's hot (20)

ODP
Xke spring boot
sourabh aggarwal
 
PDF
Spring Boot Actuator
Rowell Belen
 
PDF
Spring Boot
HongSeong Jeon
 
PPTX
Introduction to spring boot
Santosh Kumar Kar
 
PPT
Oops in Java
malathip12
 
PDF
Spring Security
Knoldus Inc.
 
PDF
Spring Framework - MVC
Dzmitry Naskou
 
PPTX
Spring boot
Pradeep Shanmugam
 
PPTX
Spring boot Introduction
Jeevesh Pandey
 
PDF
Spring Boot Interview Questions | Edureka
Edureka!
 
PPTX
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
PPSX
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
PPTX
C# classes objects
Dr.Neeraj Kumar Pandey
 
PPTX
Introduction to Maven
Onkar Deshpande
 
PPTX
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
DOCX
Spring annotations notes
Vipul Singh
 
PDF
Spring Framework - Spring Security
Dzmitry Naskou
 
PPTX
Spring Web MVC
zeeshanhanif
 
PDF
Finally, easy integration testing with Testcontainers
Rudy De Busscher
 
PPTX
Introduction to Spring Boot
Purbarun Chakrabarti
 
Xke spring boot
sourabh aggarwal
 
Spring Boot Actuator
Rowell Belen
 
Spring Boot
HongSeong Jeon
 
Introduction to spring boot
Santosh Kumar Kar
 
Oops in Java
malathip12
 
Spring Security
Knoldus Inc.
 
Spring Framework - MVC
Dzmitry Naskou
 
Spring boot
Pradeep Shanmugam
 
Spring boot Introduction
Jeevesh Pandey
 
Spring Boot Interview Questions | Edureka
Edureka!
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
C# classes objects
Dr.Neeraj Kumar Pandey
 
Introduction to Maven
Onkar Deshpande
 
React JS - A quick introduction tutorial
Mohammed Fazuluddin
 
Spring annotations notes
Vipul Singh
 
Spring Framework - Spring Security
Dzmitry Naskou
 
Spring Web MVC
zeeshanhanif
 
Finally, easy integration testing with Testcontainers
Rudy De Busscher
 
Introduction to Spring Boot
Purbarun Chakrabarti
 

Similar to Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides (20)

PPTX
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
PawanMM
 
PPTX
How to replace an XML Configuration file with a Java Configuration file in a ...
Jayasree Perilakkalam
 
PDF
Using java beans(ii)
Ximentita Hernandez
 
PPT
Spring talk111204
ealio
 
PPTX
Spring framework in depth
Vinay Kumar
 
PPT
SpringIntroductionpresentationoverintroduction.ppt
imjdabhinawpandey
 
DOC
Sel study notes
Lalit Singh
 
PPT
Spring introduction
AnilKumar Etagowni
 
PPT
Spring framework
Ajit Koti
 
PPTX
Java Course Day 23
Oleg Yushchenko
 
PDF
Toms introtospring mvc
Guo Albert
 
PDF
Struts Tags Speakernoted
Harjinder Singh
 
PPTX
ADP - Chapter 5 Exploring JavaServer Pages Technology
Riza Nurman
 
PPT
JSP Part 2
DeeptiJava
 
PDF
Introduction to Spring Framework
Rajind Ruparathna
 
PPTX
Spring core
Harshit Choudhary
 
PPTX
Spring beans
Roman Dovgan
 
PDF
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
DK Lee
 
PDF
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
PawanMM
 
How to replace an XML Configuration file with a Java Configuration file in a ...
Jayasree Perilakkalam
 
Using java beans(ii)
Ximentita Hernandez
 
Spring talk111204
ealio
 
Spring framework in depth
Vinay Kumar
 
SpringIntroductionpresentationoverintroduction.ppt
imjdabhinawpandey
 
Sel study notes
Lalit Singh
 
Spring introduction
AnilKumar Etagowni
 
Spring framework
Ajit Koti
 
Java Course Day 23
Oleg Yushchenko
 
Toms introtospring mvc
Guo Albert
 
Struts Tags Speakernoted
Harjinder Singh
 
ADP - Chapter 5 Exploring JavaServer Pages Technology
Riza Nurman
 
JSP Part 2
DeeptiJava
 
Introduction to Spring Framework
Rajind Ruparathna
 
Spring core
Harshit Choudhary
 
Spring beans
Roman Dovgan
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
DK Lee
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Ad

More from Hitesh-Java (20)

PPSX
Spring - Part 4 - Spring MVC
Hitesh-Java
 
PPSX
Spring - Part 3 - AOP
Hitesh-Java
 
PPSX
JSP - Part 2 (Final)
Hitesh-Java
 
PPSX
JSP - Part 1
Hitesh-Java
 
PPSX
Struts 2 - Hibernate Integration
Hitesh-Java
 
PPSX
Struts 2 - Introduction
Hitesh-Java
 
PPSX
Hibernate - Part 2
Hitesh-Java
 
PPSX
Hibernate - Part 1
Hitesh-Java
 
PPSX
JDBC Part - 2
Hitesh-Java
 
PPSX
JDBC
Hitesh-Java
 
PPSX
Java IO, Serialization
Hitesh-Java
 
PPSX
Inner Classes
Hitesh-Java
 
PPSX
Collections - Maps
Hitesh-Java
 
PPSX
Review Session - Part -2
Hitesh-Java
 
PPSX
Review Session and Attending Java Interviews
Hitesh-Java
 
PPSX
Collections - Lists, Sets
Hitesh-Java
 
PPSX
Collections - Sorting, Comparing Basics
Hitesh-Java
 
PPSX
Collections - Array List
Hitesh-Java
 
PPSX
Object Class
Hitesh-Java
 
PPSX
Exception Handling - Continued
Hitesh-Java
 
Spring - Part 4 - Spring MVC
Hitesh-Java
 
Spring - Part 3 - AOP
Hitesh-Java
 
JSP - Part 2 (Final)
Hitesh-Java
 
JSP - Part 1
Hitesh-Java
 
Struts 2 - Hibernate Integration
Hitesh-Java
 
Struts 2 - Introduction
Hitesh-Java
 
Hibernate - Part 2
Hitesh-Java
 
Hibernate - Part 1
Hitesh-Java
 
JDBC Part - 2
Hitesh-Java
 
Java IO, Serialization
Hitesh-Java
 
Inner Classes
Hitesh-Java
 
Collections - Maps
Hitesh-Java
 
Review Session - Part -2
Hitesh-Java
 
Review Session and Attending Java Interviews
Hitesh-Java
 
Collections - Lists, Sets
Hitesh-Java
 
Collections - Sorting, Comparing Basics
Hitesh-Java
 
Collections - Array List
Hitesh-Java
 
Object Class
Hitesh-Java
 
Exception Handling - Continued
Hitesh-Java
 
Ad

Recently uploaded (20)

PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
July Patch Tuesday
Ivanti
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PPTX
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
PDF
Complete Network Protection with Real-Time Security
L4RGINDIA
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
July Patch Tuesday
Ivanti
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
Complete Network Protection with Real-Time Security
L4RGINDIA
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 

Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides

  • 2. Page 1Classification: Restricted Agenda • Auto-wiring • Annotations based configuration • Java based configuration
  • 3. Java & JEE Training Autowiring
  • 4. Page 3Classification: Restricted Autowiring Beans • The Spring container can autowire relationships between collaborating beans without using <constructor-arg> and <property> elements • This helps cut down on the amount of XML configuration you write for a big Spring based application.
  • 5. Page 4Classification: Restricted Autowiring Modes Mode Description no This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. byName Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file. byType Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown. constructor Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised. autodetect Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.
  • 6. Page 5Classification: Restricted Autowiring - byName <!-- Definition for textEditor bean --> <bean id="textEditor" class="demo.TextEditor"> <property name="spellChecker" ref="spellChecker" /> <property name="name" value="Generic Text Editor" /> </bean> <!-- Definition for spellChecker bean --> <bean id="spellChecker" class="demo.SpellChecker"> </bean> <!-- Definition for textEditor bean --> <bean id="textEditor" class="demo.TextEditor" autowire="byName"> <property name="name" value="Generic Text Editor" /> </bean> <!-- Definition for spellChecker bean --> <!– SpellChecker spellchecker = new SpellChecker(); --> <bean id="spellChecker" class="demo.SpellChecker"> </bean> <!-- Definition for spellChecker bean --> <bean id="spellChecker2" class="demo.SpellChecker"> </bean>
  • 7. Page 6Classification: Restricted Autowiring - byType <!-- Definition for textEditor bean --> <bean id="textEditor" class="demo.TextEditor"> <property name="spellChecker" ref="spellChecker" /> <property name="name" value="Generic Text Editor" /> </bean> <!-- Definition for spellChecker bean --> <bean id="spellChecker" class="demo.SpellChecker"> </bean> <!-- Definition for textEditor bean --> <bean id="textEditor" class="demo.TextEditor" autowire="byType"> <property name="name" value="Generic Text Editor" /> </bean> <!-- Definition for spellChecker bean --> <bean id="SpellChecker" class="demo.SpellChecker"> </bean> <!-- Definition for spellChecker bean; Only one bean definition allowed.--> <bean id="SpellChecker1" class="demo.SpellChecker"> </bean>
  • 8. Page 7Classification: Restricted Autowiring - constructor <!-- Definition for textEditor bean --> <bean id="textEditor" class="demo.TextEditor"> <constructor-arg ref="spellChecker" /> <constructor-arg value="Generic Text Editor"/> </bean> <!-- Definition for spellChecker bean --> <bean id="spellChecker" class="demo.SpellChecker"> </bean> <!-- Definition for textEditor bean --> <bean id="textEditor" class="demo.TextEditor“ autowire="constructor"> <constructor-arg value="Generic Text Editor"/> </bean> <!-- Definition for spellChecker bean --> <bean id="SpellChecker" class="demo.SpellChecker"> </bean>
  • 10. Java & JEE Training Annotation Based Configuration
  • 11. Page 10Classification: Restricted Annotation Based Configuration • Starting Spring 2.5, instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration. • Annotation injection is performed before XML injection, thus the latter configuration will override the former for properties wired through both approaches.
  • 12. Page 11Classification: Restricted Switching on Annotation based configuration/wiring • Not switched on by default. • Enable it in the configuration xml file. <?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <!-- bean definitions go here --> </beans>
  • 13. Page 12Classification: Restricted Switching on Annotation based configuration/wiring • Once <context:annotation-config/> is configured, you can start annotating your code to indicate that Spring should automatically wire values into properties, methods, and constructors. • Following significant annotations are used: @Required @Autowired @Qualifier
  • 14. Page 13Classification: Restricted @Required Annotation • applies to bean property setter methods and it indicates that the affected bean property must be populated in XML configuration file at configuration time • otherwise the container throws a BeanInitializationException exception public class Student { private Integer age; private String name; @Required public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } @Required public void setName(String name) { this.name = name; } public String getName() { return name; } }
  • 15. Page 14Classification: Restricted @Autowired • provides more fine-grained control over where and how autowiring should be accomplished. • The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.
  • 16. Page 15Classification: Restricted @Autowired on setter methods • Use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. • When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method. //Student.java private Address address; @Autowired public void setAddress( Address address){ this.address = address; } <context:annotation-config/> <!-- Definition for student bean without constructor-arg --> <bean id=“student" class=“demo.Student"> </bean> <!-- Definition for address bean --> <bean id=“address" class=“demo.address"> </bean>
  • 17. Page 16Classification: Restricted @Autowired on Constructors • A constructor @Autowired annotation indicates that the constructor should be autowired when creating the bean, even if no <constructor-arg> elements are used while configuring the bean in XML file. private SpellChecker spellChecker; @Autowired public TextEditor(SpellChecker spellChecker){ System.out.println("Inside TextEditor constructor." ); this.spellChecker = spellChecker; } <context:annotation-config/> <!-- Definition for textEditor bean without constructor-arg --> <bean id="textEditor" class="demo.TextEditor"> </bean> <!-- Definition for spellChecker bean --> <bean id="spellChecker" class="demo.SpellChecker"> </bean>
  • 18. Page 17Classification: Restricted @Autowired(required=false) • By default, the @Autowired annotation => the dependency is required similar to @Required annotation. • However, you can turn off the default behavior by using (required = false) option with @Autowired. public class Student { private Integer age; private String name; @Autowired(required=false) public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } @Autowired public void setName(String name) { this.name = name; } public String getName() { return name; } }
  • 19. Page 18Classification: Restricted @Qualifier with @Autowired – remove confusion public class Profile { @Autowired @Qualifier("student1") private Student student; public Profile(){ System.out.println("Inside Profile constructor." ); } …. <context:annotation-config/> <!-- Definition for profile bean --> <bean id="profile" class="demo.Profile"> </bean> <!-- Definition for student1 bean --> <bean id="student1" class="demo.Student"> <property name="name" value="Zara" /> <property name="age" value="11"/> </bean> <!-- Definition for student2 bean --> <bean id="student2" class="demo.Student"> <property name="name" value="Nuha" /> <property name="age" value="2"/> </bean>
  • 20. Java & JEE Training Java Based Configuration
  • 21. Page 20Classification: Restricted Java based configuration using- @Configuration and @Bean import org.springframework.context.annotation.*; @Configuration public class HelloWorldConfig { @Bean public HelloWorld helloWorld(){ return new HelloWorld(); } } <beans> <bean id="helloWorld" class=“demo.HelloWorld" /> </beans> ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class); HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
  • 22. Page 21Classification: Restricted Java based configuration… Injecting bean dependency import org.springframework.context.annotation.*; @Configuration public class AppConfig { @Bean public Foo foo() { return new Foo(bar()); } @Bean public Bar bar() { return new Bar(); } } ?? Complete the exercise..
  • 23. Page 22Classification: Restricted Java based configuration - @Import @Configuration public class ConfigA { @Bean public A a() { return new A(); } } @Configuration @Import(ConfigA.class) public class ConfigB { @Bean public B a() { return new A(); } } ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);
  • 24. Page 23Classification: Restricted Specifying Bean Scope @Configuration public class AppConfig { @Bean @Scope("prototype") public Foo foo() { return new Foo(); } }
  • 25. Page 24Classification: Restricted Topics to be covered in next session • Spring AOP • What is AOP • AOP Terminologies • AOP Implementations