SlideShare uma empresa Scribd logo
1 de 26
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!

Mais conteúdo relacionado

Mais procurados

Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 

Mais procurados (20)

Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring boot
Spring bootSpring boot
Spring boot
 
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 introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
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
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Spring framework IOC and Dependency Injection
Spring framework  IOC and Dependency InjectionSpring framework  IOC and Dependency Injection
Spring framework IOC and Dependency Injection
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 

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

Spring framework
Spring frameworkSpring framework
Spring framework
Ajit Koti
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
Guo Albert
 
Struts Tags Speakernoted
Struts Tags SpeakernotedStruts Tags Speakernoted
Struts Tags Speakernoted
Harjinder Singh
 

Semelhante a Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides (20)

Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based ConfigurationSession 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
 
How to replace an XML Configuration file with a Java Configuration file in a ...
How to replace an XML Configuration file with a Java Configuration file in a ...How to replace an XML Configuration file with a Java Configuration file in a ...
How to replace an XML Configuration file with a Java Configuration file in a ...
 
Using java beans(ii)
Using java beans(ii)Using java beans(ii)
Using java beans(ii)
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Spring by rj
Spring by rjSpring by rj
Spring by rj
 
Sel study notes
Sel study notesSel study notes
Sel study notes
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Java Course Day 23
Java Course Day 23Java Course Day 23
Java Course Day 23
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
Struts Tags Speakernoted
Struts Tags SpeakernotedStruts Tags Speakernoted
Struts Tags Speakernoted
 
ADP - Chapter 5 Exploring JavaServer Pages Technology
ADP - Chapter 5 Exploring JavaServer Pages TechnologyADP - Chapter 5 Exploring JavaServer Pages Technology
ADP - Chapter 5 Exploring JavaServer Pages Technology
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring core
Spring coreSpring core
Spring core
 
Spring beans
Spring beansSpring beans
Spring beans
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
 
สปริงเฟรมเวิร์ค4.1
สปริงเฟรมเวิร์ค4.1สปริงเฟรมเวิร์ค4.1
สปริงเฟรมเวิร์ค4.1
 

Mais de Hitesh-Java

Mais de Hitesh-Java (20)

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

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

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