SlideShare a Scribd company logo
Java & JEE Training
Session 44 – 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

PPT
Spring talk111204
PDF
BP-6 Repository Customization Best Practices
PPTX
ADP- Chapter 3 Implementing Inter-Servlet Communication
PPTX
Spring Web Views
PDF
JavaServer Faces 2.0 - JavaOne India 2011
PPTX
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
 
PPTX
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
 
PDF
The Rails Way
Spring talk111204
BP-6 Repository Customization Best Practices
ADP- Chapter 3 Implementing Inter-Servlet Communication
Spring Web Views
JavaServer Faces 2.0 - JavaOne India 2011
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
 
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
 
The Rails Way

What's hot (19)

PPT
Spring framework
PDF
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
PDF
Head First Zend Framework - Part 1 Project & Application
TXT
PDF
Basic JSTL
TXT
Jsp Notes
PDF
深入淺出 MVC
PDF
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
PDF
Ajax, JSF, Facelets, Eclipse & Maven tutorials
PPT
Ionic tabs template explained
DOCX
Pom
KEY
Pimp My Confluence Plugin - AtlasCamp 2011
PPTX
Advance java session 12
PPTX
Jsp config implicit object
PDF
Angular JS blog tutorial
PDF
AtlasCamp 2013: Confluence patterns
PDF
Drupal 8 Services
PPTX
Javatwo2012 java frameworkcomparison
Spring framework
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
Head First Zend Framework - Part 1 Project & Application
Basic JSTL
Jsp Notes
深入淺出 MVC
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Ajax, JSF, Facelets, Eclipse & Maven tutorials
Ionic tabs template explained
Pom
Pimp My Confluence Plugin - AtlasCamp 2011
Advance java session 12
Jsp config implicit object
Angular JS blog tutorial
AtlasCamp 2013: Confluence patterns
Drupal 8 Services
Javatwo2012 java frameworkcomparison
Ad

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

PPSX
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
PDF
springtraning-7024840-phpapp01.pdf
PDF
2-0. Spring ecosytem.pdf
PPTX
Session 43 - Spring - Part 1 - IoC DI Beans
PDF
quickguide-einnovator-2-spring4-dependency-injection-annotations
PPSX
Spring - Part 1 - IoC, Di and Beans
PDF
Introduction to Spring Framework
PPTX
Spring essentials 1 (Spring Series 01)
PDF
Spring Framework - III
PPTX
Spring framework Controllers and Annotations
PDF
Spring 3 to 4
ODP
Spring 4 final xtr_presentation
PPT
Spring training
PPT
Story ofcorespring infodeck
PPT
Spring, web service, web server, eclipse by a introduction sandesh sharma
DOCX
Spring annotations notes
PPTX
Java Spring
PPTX
Introduction to Spring Framework
PPTX
Introduction to Spring Framework
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
springtraning-7024840-phpapp01.pdf
2-0. Spring ecosytem.pdf
Session 43 - Spring - Part 1 - IoC DI Beans
quickguide-einnovator-2-spring4-dependency-injection-annotations
Spring - Part 1 - IoC, Di and Beans
Introduction to Spring Framework
Spring essentials 1 (Spring Series 01)
Spring Framework - III
Spring framework Controllers and Annotations
Spring 3 to 4
Spring 4 final xtr_presentation
Spring training
Story ofcorespring infodeck
Spring, web service, web server, eclipse by a introduction sandesh sharma
Spring annotations notes
Java Spring
Introduction to Spring Framework
Introduction to Spring Framework
Ad

More from PawanMM (20)

PPTX
Session 48 - JS, JSON and AJAX
PPTX
Session 46 - Spring - Part 4 - Spring MVC
PPTX
Session 45 - Spring - Part 3 - AOP
PPTX
Session 42 - Struts 2 Hibernate Integration
PPTX
Session 41 - Struts 2 Introduction
PPTX
Session 40 - Hibernate - Part 2
PPTX
Session 39 - Hibernate - Part 1
PPTX
Session 38 - Core Java (New Features) - Part 1
PPTX
Session 37 - JSP - Part 2 (final)
PPTX
Session 36 - JSP - Part 1
PPTX
Session 35 - Design Patterns
PPTX
Session 34 - JDBC Best Practices, Introduction to Design Patterns
PPTX
Session 33 - Session Management using other Techniques
PPTX
Session 32 - Session Management using Cookies
PPTX
Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
PPTX
Session 30 - Servlets - Part 6
PPTX
Session 29 - Servlets - Part 5
PPTX
Session 28 - Servlets - Part 4
PPTX
Session 26 - Servlets Part 2
PPTX
Session 25 - Introduction to JEE, Servlets
Session 48 - JS, JSON and AJAX
Session 46 - Spring - Part 4 - Spring MVC
Session 45 - Spring - Part 3 - AOP
Session 42 - Struts 2 Hibernate Integration
Session 41 - Struts 2 Introduction
Session 40 - Hibernate - Part 2
Session 39 - Hibernate - Part 1
Session 38 - Core Java (New Features) - Part 1
Session 37 - JSP - Part 2 (final)
Session 36 - JSP - Part 1
Session 35 - Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design Patterns
Session 33 - Session Management using other Techniques
Session 32 - Session Management using Cookies
Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
Session 30 - Servlets - Part 6
Session 29 - Servlets - Part 5
Session 28 - Servlets - Part 4
Session 26 - Servlets Part 2
Session 25 - Introduction to JEE, Servlets

Recently uploaded (20)

PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Google’s NotebookLM Unveils Video Overviews
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PPTX
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
PDF
Event Presentation Google Cloud Next Extended 2025
PDF
Dell Pro 14 Plus: Be better prepared for what’s coming
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PPTX
ABU RAUP TUGAS TIK kelas 8 hjhgjhgg.pptx
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
DevOps & Developer Experience Summer BBQ
PDF
ai-archetype-understanding-the-personality-of-agentic-ai.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Google’s NotebookLM Unveils Video Overviews
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
Web Security: Login Bypass, SQLi, CSRF & XSS.pptx
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
GamePlan Trading System Review: Professional Trader's Honest Take
Transforming Manufacturing operations through Intelligent Integrations
A Day in the Life of Location Data - Turning Where into How.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Reimagining Insurance: Connected Data for Confident Decisions.pdf
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
Event Presentation Google Cloud Next Extended 2025
Dell Pro 14 Plus: Be better prepared for what’s coming
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
ABU RAUP TUGAS TIK kelas 8 hjhgjhgg.pptx
madgavkar20181017ppt McKinsey Presentation.pdf
DevOps & Developer Experience Summer BBQ
ai-archetype-understanding-the-personality-of-agentic-ai.pdf

Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration

  • 1. Java & JEE Training Session 44 – Spring Continued…
  • 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