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)

Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
NexThoughts Technologies
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
Mehul Jariwala
 
Spring boot
Spring bootSpring boot
Spring boot
Pradeep Shanmugam
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
Rasheed Waraich
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
Hitesh-Java
 
Spring Boot
Spring BootSpring Boot
Spring Boot
HongSeong Jeon
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
Emprovise
 
Spring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaSpring Boot Interview Questions | Edureka
Spring Boot Interview Questions | Edureka
Edureka!
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
ejlp12
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
elliando dias
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Spring beans
Spring beansSpring beans
Spring beans
Roman Dovgan
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Spring Core
Spring CoreSpring Core
Spring Core
Pushan Bhattacharya
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Serhat Can
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jaran Flaath
 
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Edureka!
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Edureka!
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
Rasheed Waraich
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
Hitesh-Java
 
Spring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaSpring Boot Interview Questions | Edureka
Spring Boot Interview Questions | Edureka
Edureka!
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
ejlp12
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Serhat Can
 
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Edureka!
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Edureka!
 

Similar to 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
PawanMM
 
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 ...
Jayasree Perilakkalam
 
Using java beans(ii)
Using java beans(ii)Using java beans(ii)
Using java beans(ii)
Ximentita Hernandez
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
ealio
 
Spring by rj
Spring by rjSpring by rj
Spring by rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
SpringIntroductionpresentationoverintroduction.ppt
SpringIntroductionpresentationoverintroduction.pptSpringIntroductionpresentationoverintroduction.ppt
SpringIntroductionpresentationoverintroduction.ppt
imjdabhinawpandey
 
Sel study notes
Sel study notesSel study notes
Sel study notes
Lalit Singh
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
AnilKumar Etagowni
 
Spring framework
Spring frameworkSpring framework
Spring framework
Ajit Koti
 
Java Course Day 23
Java Course Day 23Java Course Day 23
Java Course Day 23
Oleg Yushchenko
 
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
 
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
Riza Nurman
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
DeeptiJava
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Rajind Ruparathna
 
Spring core
Spring coreSpring core
Spring core
Harshit Choudhary
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
DK Lee
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
สปริงเฟรมเวิร์ค4.1
สปริงเฟรมเวิร์ค4.1สปริงเฟรมเวิร์ค4.1
สปริงเฟรมเวิร์ค4.1
ทวิร พานิชสมบัติ
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
srmelody
 
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
PawanMM
 
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 ...
Jayasree Perilakkalam
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
ealio
 
SpringIntroductionpresentationoverintroduction.ppt
SpringIntroductionpresentationoverintroduction.pptSpringIntroductionpresentationoverintroduction.ppt
SpringIntroductionpresentationoverintroduction.ppt
imjdabhinawpandey
 
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
 
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
Riza Nurman
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Rajind Ruparathna
 
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
자바 웹 개발 시작하기 (1주차 : 웹 어플리케이션 체험 실습)
DK Lee
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
srmelody
 
Ad

More from Hitesh-Java (20)

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

Recently uploaded (20)

Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 

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