SlideShare a Scribd company logo
1 of 11
How to replace an XML Configuration file with a
Java Configuration file in a Spring application
This is a guideline/reference document that can be used to understand how to replace
an XML Spring Bean Configuration file with a Java Spring Bean Configuration file in a
Spring application. This is a reference document for developers.
Jayasree Perilakkalam
Introduction
• This is a reference document that addresses the details regarding how
to replace an XML configuration file with a Java configuration file in a
Spring application.
• This document can also be referenced to understand the steps for
configuration using a Java Configuration file for a Spring application.
• This document does not indicate that pure Java Configuration for a
Spring application per se is better than XML configuration. It will
depend on the scope of the application whether to choose one and
not the other.
• Any questions/suggestions/comments are welcome via the comments
section below.
Capabilities Addressed
• Read “Property” values from “properties” file
• Bean configuration
Read “properties” from a file
• What is a property?
- Property is a key/value pair and is available in a file in the “resources” folder
in a Java/Spring based project
- It is entered in the format -> <key>=<value>
Read “properties” from a file
• Annotations used
- @PropertySource –> This is placed on classes annotated with @Configuration
and defines the “properties” file.
- @Value –> This is used to specify an expression on fields or methods. This
expression can be a placeholder and a property’s key can be specified here. We
can also specify default values for the property.
Read “properties” from a file
• A sample is as follows:
@Component(“examp”)
public class Example {
…
…
@Value(“${exampInt:111}”)
private int exampleInt;
@Value(“${nameProperty}”)
private String nameProp;
…
public String getNameProp() {
return nameProp;
}
…
}
Bean configuration
• Annotations used
- @Configuration -> The Java Configuration file will have @Configuration annotation.
- @ComponentScan -> This tells Spring to look for other configurations, services,
components in the package specified here. Spring will auto detect and register the
beans from the package specified. If the package specified does not exist, Spring will
scan the package of the class that has this annotation.
- @Bean -> This is placed on a method that instantiates the concrete class. It’s usually
a better practice to have return type as an interface type for this method. This serves
as the bean definition. The name as defined in the @Bean notation is same as “id” as
defined in the XML Configuration file.
- @Component -> This is used to enable auto-discovery of the particular bean (Java
object). When applied on a POJO class, Spring framework will auto-detect this class
for dependency injection.
- @EnableAspectJAutoProxy -> This is used on @Configuration classes. This enables
support for @Aspect annotation, similar to functionality found in Spring’s
<aop:aspectj-autoproxy> XML element.
Bean configuration
• A sample bean configuration is as follows:
@Configuration
@ComponentScan(basePackages=“com.examplestudy”)
@PropertySource(value={“classpath:properties/examp.properties”})
public class ExampleConfig {
…
…
@Bean(“name”)
private Name getName() {
return new Name(“Hello”, “Hello”);
}
…
}
A sample Spring Bean Configuration file
@Configuration
@ComponentScan(basePackages=“com.examplestudy”)
@PropertySource(value={“classpath:properties/examp.properties”})
public class ExampleConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
…
…
} This is a standard Spring bean. This is equivalent to <context:property-placeholder/> in a XML Config file. This is used
to resolve placeholders against the properties from a local file/environment variable/system properties.
A test app using the concepts learnt
• Run the following Java app
public class TestApp {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ExampleConfig.class);
Name name = (Name) context.getBean(“name”);
System.out.println(name);
Example examp = (Example) context.getBean(“examp”);
System.out.println(examp.getNameProp();
((AnnotationConfigApplicationContext)context).close();
}
}
// a sample “Name” class is as follows:
public class Name {
private String firstName;
private String lastName;
public Name (String firstName. String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String toString() {
return firstName + “ “ + lastName;
}
}
Conclusion
• This document is meant to be a reference guide for developing re-
usable software components and loosely coupled applications.
• References I used to create this presentation are wiki pages/internet,
my enrolled programming related courses and my past work
experience.
Thank you

More Related Content

What's hot

Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQLCoT
 
Oracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switchingOracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switchingSmitha Padmanabhan
 
.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15aminmesbahi
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.Luigi Viggiano
 
.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14aminmesbahi
 
Understanding
Understanding Understanding
Understanding Arun Gupta
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design PatternsDang Tuan
 
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres OpenMichael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres OpenPostgresOpen
 

What's hot (20)

Sub query_SQL
Sub query_SQLSub query_SQL
Sub query_SQL
 
Module 3
Module 3Module 3
Module 3
 
Ch04
Ch04Ch04
Ch04
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
Oracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switchingOracle - SQL-PL/SQL context switching
Oracle - SQL-PL/SQL context switching
 
01 oracle architecture
01 oracle architecture01 oracle architecture
01 oracle architecture
 
Oracle query optimizer
Oracle query optimizerOracle query optimizer
Oracle query optimizer
 
.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15.NET Core, ASP.NET Core Course, Session 15
.NET Core, ASP.NET Core Course, Session 15
 
plsql les01
 plsql les01 plsql les01
plsql les01
 
plsql les02
 plsql les02 plsql les02
plsql les02
 
Oracle Database View
Oracle Database ViewOracle Database View
Oracle Database View
 
plsql les06
 plsql les06 plsql les06
plsql les06
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.
 
.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14
 
Plsql les04
Plsql les04Plsql les04
Plsql les04
 
Understanding
Understanding Understanding
Understanding
 
M04 Design Patterns
M04 Design PatternsM04 Design Patterns
M04 Design Patterns
 
Synthetic models
Synthetic modelsSynthetic models
Synthetic models
 
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres OpenMichael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
 
Sql views
Sql viewsSql views
Sql views
 

Similar to Replace XML with Java Config in Spring

Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesHitesh-Java
 
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 ConfigurationPawanMM
 
DOSUG XML Beans overview by Om Sivanesian
DOSUG XML Beans overview by Om SivanesianDOSUG XML Beans overview by Om Sivanesian
DOSUG XML Beans overview by Om SivanesianMatthew McCullough
 
Introduction To Ant
Introduction To AntIntroduction To Ant
Introduction To AntRajesh Kumar
 
quickguide-einnovator-2-spring4-dependency-injection-annotations
quickguide-einnovator-2-spring4-dependency-injection-annotationsquickguide-einnovator-2-spring4-dependency-injection-annotations
quickguide-einnovator-2-spring4-dependency-injection-annotationsjorgesimao71
 
Painless Javascript Unit Testing
Painless Javascript Unit TestingPainless Javascript Unit Testing
Painless Javascript Unit TestingBenjamin Wilson
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in SpringASG
 
Different Types of Containers in Spring
Different Types of Containers in Spring Different Types of Containers in Spring
Different Types of Containers in Spring Sunil kumar Mohanty
 
chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)It Academy
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and AnnotationsAnuj Singh Rajput
 
Object Oriented Programming - Java
Object Oriented Programming -  JavaObject Oriented Programming -  Java
Object Oriented Programming - JavaDaniel Ilunga
 

Similar to Replace XML with Java Config in Spring (20)

Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
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
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
DOSUG XML Beans overview by Om Sivanesian
DOSUG XML Beans overview by Om SivanesianDOSUG XML Beans overview by Om Sivanesian
DOSUG XML Beans overview by Om Sivanesian
 
Sel study notes
Sel study notesSel study notes
Sel study notes
 
Introduction To Ant
Introduction To AntIntroduction To Ant
Introduction To Ant
 
Jstl Guide
Jstl GuideJstl Guide
Jstl Guide
 
quickguide-einnovator-2-spring4-dependency-injection-annotations
quickguide-einnovator-2-spring4-dependency-injection-annotationsquickguide-einnovator-2-spring4-dependency-injection-annotations
quickguide-einnovator-2-spring4-dependency-injection-annotations
 
Painless Javascript Unit Testing
Painless Javascript Unit TestingPainless Javascript Unit Testing
Painless Javascript Unit Testing
 
Mule properties
Mule propertiesMule properties
Mule properties
 
Mule properties
Mule propertiesMule properties
Mule properties
 
Dependency Injection in Spring
Dependency Injection in SpringDependency Injection in Spring
Dependency Injection in Spring
 
Different Types of Containers in Spring
Different Types of Containers in Spring Different Types of Containers in Spring
Different Types of Containers in Spring
 
Using java beans(ii)
Using java beans(ii)Using java beans(ii)
Using java beans(ii)
 
MyBatis
MyBatisMyBatis
MyBatis
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and Annotations
 
Karate DSL
Karate DSLKarate DSL
Karate DSL
 
Object Oriented Programming - Java
Object Oriented Programming -  JavaObject Oriented Programming -  Java
Object Oriented Programming - Java
 

Recently uploaded

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 

Replace XML with Java Config in Spring

  • 1. How to replace an XML Configuration file with a Java Configuration file in a Spring application This is a guideline/reference document that can be used to understand how to replace an XML Spring Bean Configuration file with a Java Spring Bean Configuration file in a Spring application. This is a reference document for developers. Jayasree Perilakkalam
  • 2. Introduction • This is a reference document that addresses the details regarding how to replace an XML configuration file with a Java configuration file in a Spring application. • This document can also be referenced to understand the steps for configuration using a Java Configuration file for a Spring application. • This document does not indicate that pure Java Configuration for a Spring application per se is better than XML configuration. It will depend on the scope of the application whether to choose one and not the other. • Any questions/suggestions/comments are welcome via the comments section below.
  • 3. Capabilities Addressed • Read “Property” values from “properties” file • Bean configuration
  • 4. Read “properties” from a file • What is a property? - Property is a key/value pair and is available in a file in the “resources” folder in a Java/Spring based project - It is entered in the format -> <key>=<value>
  • 5. Read “properties” from a file • Annotations used - @PropertySource –> This is placed on classes annotated with @Configuration and defines the “properties” file. - @Value –> This is used to specify an expression on fields or methods. This expression can be a placeholder and a property’s key can be specified here. We can also specify default values for the property.
  • 6. Read “properties” from a file • A sample is as follows: @Component(“examp”) public class Example { … … @Value(“${exampInt:111}”) private int exampleInt; @Value(“${nameProperty}”) private String nameProp; … public String getNameProp() { return nameProp; } … }
  • 7. Bean configuration • Annotations used - @Configuration -> The Java Configuration file will have @Configuration annotation. - @ComponentScan -> This tells Spring to look for other configurations, services, components in the package specified here. Spring will auto detect and register the beans from the package specified. If the package specified does not exist, Spring will scan the package of the class that has this annotation. - @Bean -> This is placed on a method that instantiates the concrete class. It’s usually a better practice to have return type as an interface type for this method. This serves as the bean definition. The name as defined in the @Bean notation is same as “id” as defined in the XML Configuration file. - @Component -> This is used to enable auto-discovery of the particular bean (Java object). When applied on a POJO class, Spring framework will auto-detect this class for dependency injection. - @EnableAspectJAutoProxy -> This is used on @Configuration classes. This enables support for @Aspect annotation, similar to functionality found in Spring’s <aop:aspectj-autoproxy> XML element.
  • 8. Bean configuration • A sample bean configuration is as follows: @Configuration @ComponentScan(basePackages=“com.examplestudy”) @PropertySource(value={“classpath:properties/examp.properties”}) public class ExampleConfig { … … @Bean(“name”) private Name getName() { return new Name(“Hello”, “Hello”); } … }
  • 9. A sample Spring Bean Configuration file @Configuration @ComponentScan(basePackages=“com.examplestudy”) @PropertySource(value={“classpath:properties/examp.properties”}) public class ExampleConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } … … } This is a standard Spring bean. This is equivalent to <context:property-placeholder/> in a XML Config file. This is used to resolve placeholders against the properties from a local file/environment variable/system properties.
  • 10. A test app using the concepts learnt • Run the following Java app public class TestApp { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(ExampleConfig.class); Name name = (Name) context.getBean(“name”); System.out.println(name); Example examp = (Example) context.getBean(“examp”); System.out.println(examp.getNameProp(); ((AnnotationConfigApplicationContext)context).close(); } } // a sample “Name” class is as follows: public class Name { private String firstName; private String lastName; public Name (String firstName. String lastName) { this.firstName = firstName; this.lastName = lastName; } public String toString() { return firstName + “ “ + lastName; } }
  • 11. Conclusion • This document is meant to be a reference guide for developing re- usable software components and loosely coupled applications. • References I used to create this presentation are wiki pages/internet, my enrolled programming related courses and my past work experience. Thank you