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)

PPT
Java Persistence API (JPA) Step By Step
Guo Albert
 
PPTX
Spring boot - an introduction
Jonathan Holloway
 
PPTX
JPA For Beginner's
NarayanaMurthy Ganashree
 
PPSX
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
PDF
Spring Framework - Core
Dzmitry Naskou
 
PDF
Spring framework core
Taemon Piya-Lumyong
 
PPTX
Spring Boot and REST API
07.pallav
 
PDF
Spring Data JPA
Knoldus Inc.
 
PPT
Spring Boot in Action
Alex Movila
 
PDF
Spring Framework
NexThoughts Technologies
 
PPTX
Introduction to Spring Framework
Serhat Can
 
PPTX
Angular modules in depth
Christoffer Noring
 
PPS
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
PPTX
Reactjs
Mallikarjuna G D
 
PDF
AEM Sightly Deep Dive
Gabriel Walt
 
PPTX
Spring framework Controllers and Annotations
Anuj Singh Rajput
 
PDF
Spring Data JPA
Cheng Ta Yeh
 
PDF
Spring Boot
koppenolski
 
PDF
Spring boot jpa
Hamid Ghorbani
 
PPTX
ASP.NET Web API
habib_786
 
Java Persistence API (JPA) Step By Step
Guo Albert
 
Spring boot - an introduction
Jonathan Holloway
 
JPA For Beginner's
NarayanaMurthy Ganashree
 
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Spring Framework - Core
Dzmitry Naskou
 
Spring framework core
Taemon Piya-Lumyong
 
Spring Boot and REST API
07.pallav
 
Spring Data JPA
Knoldus Inc.
 
Spring Boot in Action
Alex Movila
 
Spring Framework
NexThoughts Technologies
 
Introduction to Spring Framework
Serhat Can
 
Angular modules in depth
Christoffer Noring
 
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
AEM Sightly Deep Dive
Gabriel Walt
 
Spring framework Controllers and Annotations
Anuj Singh Rajput
 
Spring Data JPA
Cheng Ta Yeh
 
Spring Boot
koppenolski
 
Spring boot jpa
Hamid Ghorbani
 
ASP.NET Web API
habib_786
 

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
 
PDF
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
DK Lee
 
PDF
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
PPTX
สปริงเฟรมเวิร์ค4.1
ทวิร พานิชสมบัติ
 
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
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
DK Lee
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
สปริงเฟรมเวิร์ค4.1
ทวิร พานิชสมบัติ
 
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)

PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 

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