Spring Framework – What all there ?
Spring Framework is a popular open-source framework for building Java-based applications.
It simplifies development by providing comprehensive infrastructure support, including dependency injection and aspect-oriented programming.
It promotes modular and reusable code, enhancing the scalability and maintainability of applications. Spring facilitates the creation of enterprise-level software with features like data access, transaction management, and model-view-controller (MVC) architecture.
Overall, it streamlines Java development and promotes best practices for building robust, flexible applications.
- Spring-CORE
- Spring-JDBC
- Spring-AOP
- Spring-TX
- Spring-ORM
- Spring-WEB-MVC
- Spring-Security[Optional]
Introduction – Enterprise application development
Enterprise : It is a Business Organization, where business is going on for the Services.
A group of organizations running under a single label is called an Enterprise.
Enterprise Application: It is a software application, it was prepared to simplify the business processing of the Enterprises.
Enterprise Applications Architecture – Layered approach
To prepare an Enterprise application we have to use the following layers.
- User Interface Layer / Presentation layer.
- Business Processing Layer / Business Layer
- Data Storage And Access Layer / Persistence Layer
1. User Interface Layer or Presentation Layer
- It is a top most layer in the Enterprise Applications.
- Its main purpose is to improve Look and Feel to the Enterprise Applications.
- It is able to provide a very good environment to get the data from the Users in order to send to the Enterprise Applications.
- It will provide a very good environment to define and execute all the java Script functions in order to perform the Client Side Data Validations.
- It will provide a very good environment to send different types of the requests like GET, POST, HEAD, TRACE, OPTIONS, DELETE, PUT….. to the Server side applications.
- To prepare User Interface Layer in the Enterprise Applications we have to use a separate logic called Presentation logic.
- In the Enterprise Applications, to prepare presentation logic we will use the technologies like
HTML, CSS, BOOTSTRAP, JAVA SCRIPT, Angular, React JS, ………..
2. Business Processing Layer
- It is the heart of the Enterprise applications.
- It will provide a very good environment to define and execute all the business rules and regulations which are required by the Clients.
- To prepare the Business Processing Layer we have to use a separate logic called Business Logic.
- To prepare Business Logic we will use the technologies and tools like Servlets, Java Beans, Business Components in MVC based applications, EJBs-Session Beans,….
3. Data Storage And Access layer
- It is the bottom most layer in the Enterprise applications.
- Its main purpose is to connect with the Databases in order to perform the database operations from the enterprise applications.
- To prepare this layer we have to use a separate logic called Persistence Logic.
- To prepare Persistence logic in the enterprise applications we have to use a set of technologies and tools like JDBC, Hibernate, JPA, Spring JDBC, Spring ORM, Spring Boot Data JDBC, Spring Boot DATA JPA….
Types of Enterprise applications
There are two types of Enterprise Applications.
- Web Applications
- Distributed Applications
What is a distributed application – in a distributed application, different parts of the software (components or services) run on separate computers or servers and communicate with each other to accomplish a common goal.
This approach helps improve performance, scalability, and reliability, as tasks can be divided among multiple machines, and if one part fails, it doesn’t bring down the entire application. Think of it as teamwork among computers to make software work efficiently.
Q)What are the differences between Web Applications and Distributed Applications?
- Web Application is a Client-Server Application, where the complete application logic is distributed at the same Server machine.
Distributed Application is a Client-Server Application, where the complete application logic is distributed over the multiple machines like Client machine and the Server Machine.
- In web applications, the Client is fixed, that is Browser.
In the Distributed applications, Client is not fixed, it is variable , it may be a Java program with main() method, it may be an applet, it may be a server side program like a Servlet or a JSP , it may be a framework application like Struts, JSF and Spring applications,…..
- To prepare Web applications we will use a set of technologies called Web Technologies like CGI, Servlets, JSPs,….
To prepare Distributed applications we will use a set of technologies called Distributed technologies like Socket Programming , RMI, CORBA, EJBs, Web Services.
- The main intention of the web applications is to generate dynamic responses with very good Look and Feel.
The main intention of the Distributed applications is to establish communication between Local machine and Remote Machine and to access Remote Services from the Local machine which are available at the remote machine.
- Web Applications are executed by both Web Servers and Application Servers.
Distributed Applications are executed by only Application Servers.
- Web application is the collection of the web components, here to execute the Web components we will use Web Containers like Servlet Containers, JSP Containers,….
Distributed application is the collection of the Distributed components, where to execute the Distributed components we will use the distributed containers like EJB Container,….
If we want to prepare an Enterprise application we have to use both Web and Distributed applications as layers.
Enterprise Applications = Web Appl + Distributed Appl.
Enterprise applications – Design Models
To prepare Web Applications we will use the following design Models.
- Model-I Arch.
- Model-II Arch.
Model-I Web Application Architecture:
- Model-I Web Application Architecture is an outdated architecture, it was used at the starting point of the web applications.
- In Model-I web application Architecture, we will use a JSP page as controller and as a View part and a Java Bean component as a Model.
- In Model-I web application architecture, a JSP page as a controller , it must control the total web application and its flow of execution, so this architecture is also called “Page Centric Architecture”.
- In Model-I web application architecture, a JSP page is acting as a Front-Controller, it must take all the requests from the clients, so this architecture is also called “JSP-Front Architecture”.
- In Model-I web application architecture we will use a single JSP page as Controller, to fulfill all the controller responsibilities existing JSP capabilities are not sufficient, so we need to write java code inside the JSP pages, it is against the JSP rules and regulations.
- In Model-I web application architecture, we will use a set of JSP pages as Controller and View part, there is no clear cut separation between the controller components and View components, it represents Tightly coupled design, it is not suggestible in the web applications.
Model-II Web Application Architecture – MVC:
- In Model-II Web application architecture , we will use a Servlet as a controller, so this architecture is called Servlet-Centric Architecture.
- In Model-II web application architecture, we will use a Servlet as a front controller, so this architecture is also called “Servlet Front Architecture”.
- In Model-II web application architecture we will use a servlet as controller, a set of Html, Jsp pages as View part and a Java bean, EJB component or Hibernate,… as Model components.
- In Model-II web application Architecture we will provide controller layer and the View layer separately, it represents Loosely coupled Design, it is suggestible for the web applications.
Model-II web applications architecture follows MVC Design Pattern internally, so it is also called MVC Arch.
Some frameworks like Struts, JSF and Spring WEB MVC are designed on the top of the Model-II Arch , so these web frameworks are called MVC based Frameworks.
MVC Arch rules and Regulations
- In MVC based web applications, we must use a servlet as controller and a set of Jsp pages as View Part, we must not interchange the controller and view components.
- In MVC based web applications, the Controller component must receive all the requests from the Clients and the View component must send responses to the client.
- The Controller component must interact with the Model component to set users data , not to get the users data and View Component must interact with the Model components to get the users data in order to render the response.
- The controller and the View components must not interact with the Databases directly, they must interact with the databases through the Model components.
- IN MVC based web applications, only one Front controller must be provided, so it must be a singleton , but we can provide any number model components and View components as per the requirement.
- In MVC based web applications we will use multiple JSp pages as view part, but all the JSPpages must be Java code less.
- In MVC based web applications we will use multiple JSP pages as View part, but we must not provide PAGE-to-PAGE communication , where we must provide PAGE-CONTROLLER-PAGE communication.
Why & Need to use Frameworks ?
Framework – in simple terms, it means a readily available solution or a template to developing applications. It is like an abstraction provided on top of technology to simplify application development.
Q) To prepare web applications we already have Web Technologies like Servlets, JSPs,…IDEs like Eclipse, intelliJ ,…. Servers like Tomcat, Weblogic,..Model Architectures like Model-I arch , Model-II arch,…. Still, what are the requirements of the Frameworks?
In all the Enterprise applications, some components like Front Controllers, Bean components, some generic Services like Authentication, Authorization, Internationalization, Logging, data Validations,….. are common in all the enterprise applications and they will take the 70% of the enterprise applications implementation.
Even though the above 70% of the implementation is common, still if we provide that 70% of the implementation in the enterprise applications explicitly, it may increase the overall Application development time, it will increase the overall application development cost and it will reduce the applications productivity.
To overcome the above problems, some third party vendors have provided their own products which provide the above 70 % common implementation of the enterprise applications as predefined implementations , here the third party products which provide the applications common implementations called “Frameworks”.
In enterprise applications, Frameworks will provide the following advantages.
- Frameworks will provide the common components like Front controller, Bean components,…. As predefined elements.
- Frameworks will provide the generic Services like Internationalization, Data Validations, Logging,… as predefined services.
- Frameworks will provide a standard template to prepare the enterprise applications.
- Frameworks will provide a standard flow of execution to the applications.
- Frameworks will reduce the application development time.
- Frameworks will reduce the application development cost.
- Frameworks Supports parallel development.
- Frameworks will improve the Application productivity.
1. Framework is pre fabricated Software components that Developers can reuse, share and customize to simplify the enterprise application development.
2. Framework is a Semi implemented application, which provides the 70% of the implementation as predefined in order to simplify the application development.
3. Framework is the collection of APIs, tools and technologies, which are used to simplify the application development.
Types of Frameworks
There are two types of Frameworks.
- Web Frameworks
- Application Frameworks
Q) What is the difference between Web Frameworks and Application Frameworks?
Web Frameworks are able to provide a very good environment to design and execute only Web applications.
EX: Struts, JSF,….
Application Frameworks are able to provide a very good environment to prepare all the types of applications like Standalone Applications, Web Applications, Distributed applications, Database related applications,…
EX: Spring Framework
Q)What are the differences between Spring Framework , Struts and JSF frameworks?
1. Struts and JSF are the web frameworks , they are useful to prepare and execute only web applications.
Spring is an Application Framework, it is useful to prepare any type of application like Standalone Applications, Web Applications, Distributed applications, Database related applications,….
2. Struts and JSF are mainly to provide a Web layer in the enterprise applications.
Spring is able to provide all the layers of the enterprise applications.
3. Struts is a controller Layered framework, it has a very good focus on the controller layer.
JSF is a View Layered Framework, it has a very good focus on the View layer.
Spring is a Framework, it will have focus on all the layers of the enterprise applications.
4. Struts and JSF are heavy weight Frameworks.
Spring Framework is a lightweight framework.
5. Struts and JSF are more API dependent.
Spring is less API dependent.
6. It is very difficult to perform Debugging and Testing in the Struts and JSF applications , because Struts and JSF are more API dependent.
It is very simple to perform Debugging and Testing in the Spring applications, because Spring is less API dependent.
7. Struts and JSF do not have AOP Layers.
Spring Framework has an AOP layer.
8. Struts and JSF do not have inbuilt Transactions support.
Spring Framework is able to provide predefined Transactions Support.
9. Struts and JSF are not having very good layers for integrating the other applications like JDBC, Hibernate, EJBs,….
Spring Framework has a very good integration layer to integrate the other frameworks applications like JDBC, Hibernate, Struts and JSF applications,….
10. Struts and JSF are able to follow MVC Design Pattern and its co related design patterns like Factory method, Singleton classes,…
Spring Framework is able to follow more Design patterns like Inversion of Control,… along with the MVC and its co related Design Patterns.
11. Struts and JSF are not modularized Frameworks.
Spring Framework is a Modularized Framework.
12. If we execute a simple action in Struts and JSF applications, the Complete Struts JSF frameworks must be loaded.
In Spring applications, to perform a particular action the Spring Framework will load only the required module instead of loading all the modules.
Struts/JSF – invasive frameworks
public class LoginAction extends/implements Action{
public ForwardAction execute(ActionForm af, ActionForward af,
HttpServletRequest req, HttpServletResponse resp)throws Exception{
—----Application Logic—---
}
}
Spring Framework – non-invasive framework
Public class LogicAction{
private String uname;
private String upwd;
public String checkLogin(){
—--
}
}
How Spring helps in Application Development ?
Let’s take an example of application development :
End-to-end applications can be developed using Spring Framework.
Spring Framework can be used at all layers of application development.
Overview of the Spring Framework Modules
Spring is a modularized framework. Entire spring framework consists of multiple modules. Base of all other modules is the Spring Core.
Spring Framework is very versatile – meaning, the framework can easily gel with other technologies, like ORM – Hibernate, Struts, etc. It is not like, when you are developing an application, you have to use an end-to-end Spring framework only in all layers of app development.
Spring Framework can be easily integrated with other modules/layers with different technology or framework being used.
Most Spring Framework modules are non-invasive. It will not force you to extend any of its classes (or) implement any interface.
Spring Core Module:
This module is able to provide the basic Spring components like IOC Containers, Beans Management and their lifecycle, Dependency Injection principles,….. Which are available in Spring Framework.
Spring JDBC/DAO Module:
By Using Plain Jdbc we are able to prepare Jdbc applications with the following steps.
1. Load And Register Driver:
Class.forName(“com.mysql.cj.jdbc.Driver”);
2. Establish Connection between Java application and the Database:
Connection con = DriverManager.getConnection(
“jdbc:mysql://localhost:3306/durgadb”,“root”,”root”);
- Create a Statement object:
Statement st = con.createStatement();
- Write and Execute SQL Queries:
ResultSet rs = st.executeQuery(“select * from emp1”);int rowCount = st.executeUpdate(“update ep1 set ESAL = ESAL + 500 where ESAL < 10000”);
- Close the Resources:
rs.close();
st.close();
con.close();
In the above Jdbc applications the steps like Load and Register Driver, Establish Connection between java application and the Database, Create Statement or PreparedStatement and CallableStatement, Close the resources are repeatable steps at each and every Jdbc application, these repeatable steps are called “Boilerplate Code”, it is not suggestible in the enterprise applications.
In the above Context, Spring JDBC module is able to abstract the above Boilerplate code and provides a simple environment in the form of XXXTemplate classes to perform the database operations.
Spring AOP Module:
Spring AOP module is able to provide a very good environment to integrate the generic services like logging, Internationalization, Security,Exception Handling,… with the enterprise applications.
If we want to prepare an enterprise application by using the conventional Object Oriented Programming then we have to provide the implementation by combining both the Services logic and Business logic, this approach will provide tightly coupled design, it will reduce shareability and Reusability.
To overcome the above problem, we have to apply Aspect orientation over the Object Oriented programming. IN the case of Aspect orientation, we will separate the Services logic from the Business logic , we will declare each and every Service as an aspect like Logging Aspect, Authentication Aspect,… and we will inject these Aspects into the Program execution at runtime as per the requirement.
The above Aspect orientation is able to provide loosely coupled design in the Enterprise applications and they will provide more reusability and Shareability.
Spring ORM:
The main purpose of the Spring ORM module is to integrate any ORM implemented Applications with the Spring Applications.
In the Spring based Enterprise applications, if we want to integrate ORM implemented tools like JPA, Hibernate, Open JPA,iBatis,….. We have to use the Spring ORM module.
Spring Transactions Module:
In the enterprise applications we will perform the database operations , as part of the database operations we need Transactions support like to perform commit or rollback , Isolation levels, Transaction behaviors,….. To provide all these Transactions support Spring Framework has provided a separate module in the form of Spring-Transactions Module.
Spring WEB Module:
The main purpose of the Spring WEB Module is to integrate the MVC based framework applications like Struts, JSF,… with the Spring applications.
Spring WEB MVC Module:
The main purpose of this module is to prepare MVC based web applications like Struts applications, JSF applications,….
Spring Boot is a way to use Spring framework to develop Spring applications very easily and quickly.
Spring History
Home: Interface1
Author: Rod Jhanson.
Objective: To accelerate enterprise application development.
Type: Application Framework.
Freeware / Licensed: Freeware and Open Source Software.
Initial Version: Spring 1.x
Latest version: Spring 6.x
Designed on : J2SE, Servlets API, JSPS API,…
Website: spring.io
Spring 1.x Version Modules:
Spring 2.x version Modules:
Spring 3.x version Modules:
Spring 4.x, 5.x, 6.x
Spring Framework – Basic Principles
Configuration – is a way to talk from Java code to Spring framework to tell what Spring framework should do (or) what help you need from Spring framework. The communication can help in following ways :
Spring Framework – Spring Core – based on 2 principles :
a. Inversion Of Control
b. Dependency Injection
Suppose, I have couple of classes like below :
If we have to use display() method of class D in class C, then :
Option 1 – Composition – Create an object of class D inside class C, and using the object, call the display() method.
Option 2 – Inheritance – Let class C extend class D, then display() method is inherited to class C. Once this is done, we can directly use the display() method.
Above 2 approaches, we call them tightly coupled approaches.
How will the Spring framework come as a rescue to us ?
Entire funda of the spring framework is loose coupling.
Behavioral design pattern – how to change algorithm at run time – strategy design pattern – code to interface, don’t use direct classes.
Example of Loose Coupling :
DeliveryService.java
package com.rndayala.java;
public interface DeliveryService
{
boolean courierService(double amount);
}
BlueDart.java
package com.rndayala.java;
public class BlueDart implements DeliveryService {
@Override
public boolean courierService(double amount) {
System.out.println("Delivery Service using BlueDart courier service : " + amount);
return true;
}
}
FedEx.java
package com.rndayala.java;
public class FedEx implements DeliveryService {
@Override
public boolean courierService(double amount) {
System.out.println("Delivery Service using FedEx courier service : " + amount);
return true;
}
}
Amazon.java
package com.rndayala.java;
// Loose coupling example
// target class
public class Amazon {
// FedEx, BlueDart, FirstFlight -- these are all dependent objects
private DeliveryService service;
public void setService(DeliveryService service) {
this.service = service;
}
public boolean initiateDelivery(double amount) {
return service.courierService(amount);
}
}
Main application file : LaunchApp.java
package com.rndayala.java;
public class LaunchApp {
public static void main(String[] args) {
Amazon a = new Amazon();
a.setService(new FedEx()); // setter injection
boolean b = a.initiateDelivery(1000.0);
}
}
Steps to Prepare First Spring Application
- Download and Install Spring Framework.
- Make Ready Java[17] software, One IDE Software[IntelliJ Idea, Eclipse, STS],….
- Prepare a Java Project by using IDE.
- Add all the Spring JAR files to the Java project as a library.
- Prepare a Bean component.
- Prepare Spring Configuration File.
- Prepare Test Application.
- Execute the Test Application.
Download and Install Spring Framework:
- Open the below url in the Browser.
https://repo.spring.io/ui/native/milestone/org/springframework/spring/6.0.0-RC2
- Select “spring-6.0.0-RC2-dist.zip” link.
- Copy the “spring-6.0.0-RC2-dist.zip” file to the Softwares folder.
- Unzip the ““spring-6.0.0-RC2-dist.zip” file
Make Ready Java[17] software, One IDE Software[IntelliJ Idea, Eclipse, STS],….
You need to have the respective softwares installed.
Prepare a Java Project by using IDE:
Create a new project in IDE
Add all the Spring JAR files to the Java project as a library.
To prepare and execute Spring CORE Module related applications we have to add the following JAR files to the Project.
- spring-core-6.0.0-RC2.jar
- spring-beans-6.0.0-RC2.jar
- spring-context-6.0.0-RC2.jar
- spring-context-support-6.0.0-RC2.jar
- spring-expression-6.0.0-RC2.jar
To Add the above JAR files to the Java project we have to use the following actions.
Eclipse IDE
- Right Click on the Project.
- Select the “Properties”.
- Select the “Java Build Path”.
- Select the “Libraries” tab.
- Select the “classpath”.
- Click on the ”Add External Jar Files…” button.
- Select all the above specified jar files.
- Click on the “OK” button.
- Click on the “OK” button.
Adding all the above jar files to each and every Spring project is a difficult task, so we need to create a Library with all the required Spring JAR files.
- Right Click on the “Project”.
- Select the “Properties”.
- Select the “Java Build Path”.
- Select the “Libraries”.
- Select the “Classpath”.
- Click on the “Add library…”.
- Select “User library”.
- Click on the “Next” button.
- Click on the “user Libraries”.
- Click on the “New” Button.
- Provide Library Name “Spring6_Lib”.
- Click on the “Add External Jars”.
- Select all the required Spring Jar files.
- Click on the “Open” button.
- Click on the “Apply And Close” button.
- Click on the “Finish” button.
- Click on the “Apply and Close” button.
IntelliJ Idea
- Right Click on the Project.
- Select “Open Module Settings”.
- Select the “Dependencies”.
- Click on the + symbol.
- Select “Jars or Directories”.
- Select the required Spring JAR files.
- Click on the “OK” button.
Adding all the above jar files to each and every Spring project is a difficult task, so we need to create a Library with all the required Spring JAr files.
- Right Click on the Project.
- Select “Open Module Settings”.
- Select the “Dependencies”.
- Click on the + Symbol.
- Select “Library”.
- Select the “Global Library”.
- Click on the “New Library” button and select “Java”.
- Select all the required Spring JAR files.
- Click on the “Open” button.
- Provide Library Name : Spring6_Lib
- Click on the “Add Selected”.
Prepare a Bean component – POJO Classes
Java Bean is a Reusable component, it is able to manage the state of a particular entity.
Java Bean is a simple Java class, it must have private properties and the respective setter and getter methods.
In general, Java bean classes are available in the following forms in the different technologies and tools.
Struts —-------> ActionForms
JSF —----------> Backing Bean
Hibernate —----> Entity Bean , POJO class.
Spring —-------> POJO class.
To prepare bean components in the Spring applications we have to use the following rules and regulations.
- In Spring based applications, Every bean component must be a POJO[Plain Old Java Object] class, it is a normal java bean class, it must not implement or extend any predefined library[classes and interfaces].
Note: It is exceptional for the java.io.Serializable marker interface.
- In Spring based applications, every Java bean class must be a public, non abstract and a non final class.
- The main purpose of declaring bean class as public is to bring bean class scope to the IOContainer in order to create objects.
- The main purpose of declaring bean class as a non abstract class is to allow the creation of objects for the bean classes.
- In the applications, there is a requirement to extend one bean class to another bean class to improve code reusability, here to extend one bean class to another bean class the respective bean classes must not be declared as final.
- In bean classes, every property must be declared as private and every method or behavior must be declared as public in order to improve Encapsulation.
- In bean classes, for every property we must provide a separate setXXX() method and getXXX() method.
- In Java bean classes, it is suggested to override the Object class provided equals() method in the bean class in order to compare two bean objects on the basis of a particular parameter.
- In Java bean classes, it is suggested to override hashcode() method in order to provide hashcode values as per the requirement.
- In javabean components, it is suggested to override the toString() method in order to display our own data in place of “ClassName@RefValue”.
Employee.java
public class Employee{
private int eno;
private String ename;
private float esal;
private String eaddr;
setXXX()
getXxx()
....
}
Note: In Spring based applications, we will define business methods in the bean classes only along with the setXXX() methods and getXXX() methods.
Prepare Spring XML Configuration File
Spring Configuration file is an XML file, it is able to provide metadata or description to the IOC Container about to create objects for bean components and their injections.
In Spring based applications, we will provide any name to the Configuration file, but the suggestible name is “applicationcontext.xml” or Spring.xml or Spring-Config.xml.
In Spring applications, if we want to use bean classes , first we must configure these bean classes and their properties in the Spring configuration file in order to create objects for the bean classes, if the bean classes are not configured in the Spring configuration file then that bean classes are not recognized by the IOC Container to create bean objects.
To provide bean classes configuration in the Spring configuration file we must use the following xml tags.
<beans —-XSD—-- >
<bean id=”---” class=”---”>
—------
</bean>
</beans>
The “id” attribute in the <bean> tag will take an identity name to the bean object in order to retrieve bean objects from the container.
Where “class” attribute in <bean> tag will take the fully qualified name of the bean class.
<beans —-- >
<bean id=”welcomeBean” class=”com.durgasoft.beans.Wellcome”/>
<beans>
Prepare Test Application – Instantiate IOC Container
The main purpose of the Test Application is to create an IOC Container [ApplicationContext] , get the Bean components from the IOC Container and access the business methods.
To create the ApplicationContext object we have to use the following instruction.
ApplicationContext applicationContext =
new ClasspathXmlApplicationContext(“Spring-Config.xml”);
When we execute the above instruction, ApplicationContext will perform the following actions.
- ApplicationContext Container will take the name and location of the Spring configuration file.
- ApplicationContext container will load and parse the Spring configuration file.
- After parsing the Spring Configuration file, ApplicationContext Container will read all the beans configuration details from the String Configuration file.
- ApplicationContext Container will recognize all the bean classes and perform the following actions.
- Loading all the bean classes.
- Instantiate the Bean classes.
- Initialize the Bean objects.
- Maintain all the bean class objects along with their identities[id attribute values] in the ApplicationContext.
To get a particular Bean object from the IOC Container , we have to use the following method from ApplicationContext.
public Object getBean(String beanIdentity);Employee emp = (Employee)applicationContext.getBean(“employee”);
After getting the bean object from the ApplicationContext , access the business methods.
Example 1 :
Welcome.java
package com.durgasoft.beans;
public class Welcome {
public String sayWelcome() {
return "Welcome To Spring Programming";
}
}
Spring-Config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="welcome" class="com.durgasoft.beans.Welcome"/>
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Welcome;
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("Spring-Config.xml");
Welcome welcome = (Welcome) applicationContext.getBean("welcome");
String message = welcome.sayWelcome();
System.out.println(message);
}
}
Example 2:
Wish.java
package com.durgasoft.beans;
import java.time.LocalTime;
public class Wish {
public String sayWish() {
String message = "";
LocalTime time = LocalTime.now();
int hour = time.getHour();
if(hour < 12) {
message = "Good Morning!";
}else if(hour < 17) {
message = "Good Afternoom!";
}else if(hour < 24) {
message = "Good Evening!";
}
return "Hello User, "+message;
}
}
Spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="wish" class="com.durgasoft.beans.Wish"/>
</beans>
Test.java
package com.durgasoft.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.durgasoft.beans.Wish;
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("Spring-Config.xml");
Wish wish = (Wish) applicationContext.getBean("wish");
// Wish wish = applicationContext.getBean(Wish.class);
System.out.println(wish.sayWish());
}
}
In Spring applications, we will use more bean classes, where we will define the number of properties and their respective setter and getter methods as per the requirement.
In the above context, to provide values to the properties of the Bean objects we have to configure the properties in the Spring configuration file.
To configure the bean properties in the Spring configuration file we have to use the following XML tags under <bean> tag.
<beans —- >
<bean name=”--” class=”--”>
<property name=”---” value=”--”/>
—----
</bean>
</beans>
Where the <property> tag represents a single bean property.
Where the “name” attribute in the <property> tag will provide the property name that we have defined in the bean class.
Where the “value” attribute in the <property> tag will provide a particular value to the bean property.
Example 3: config file with setter injection
public class Wish{
private String name;
private String message;
setXXX() and getXXX()
}
<beans>
<bean name=”Wish” class=”com.durgasoft.beans.Wish”>
<property name=”name” value=”Durga”/>
<property name=”message” value=”Good Morning”/>
</bean>
</beans>
In the Test application, if we create the ApplicationContext object, the ApplicationContext will read the data from the <property> tags of the respective bean configuration in the Spring configuration file and the ApplicationContext will store the data into the bean object by executing the respective setter methods after the bean instantiation.
Wish.java
package com.durgasoft.beans;
public class Wish {
private String name;
private String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String sayWish(){
return "Hello "+name+", "+message;
}
}
Spring-Config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="wish" class="com.durgasoft.beans.Wish">
<property name="name" value="Durga"/>
<property name="message" value="Good Morning!"/>
</bean>
</beans>
Main.java
import com.durgasoft.beans.Wish;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("Spring-Config.xml");
Wish wish = (Wish) applicationContext.getBean("wish");
System.out.println(wish.sayWish());
}
}
Where can we have Spring configuration file ?
Q) What are the possible locations of the Spring configuration file in the Spring applications?
- Directly under the application folder.
- Directly under the src folder.
- By Preparing a package under the src folder.
- By Preparing a resources folder.
If we provide the configuration file under the src location and the resources location then the ApplicationContext will recognize the Spring configuration file directly, no need to provide the absolute path of the Spring configuration file to the ClasspathXmlApplicationContext.
ApplicationContext applicationContext = new ClasspathXmlApplicationContext(“Spring-Config.xml”);
If we provide the Spring configuration file under a package in the src folder then we must provide the relative path of the Spring configuration file w.r.t the src folder.
ApplicationContext applicationContext = new ClasspathXmlApplicationContext(“/com/durgasoft/config/Spring-Config.xml”);
If we provide the Spring Configuration file under the application folder then we have to use FileSystemXmlApplicationContext in place of ClasspathXmlApplicationContext to get the Spring Configuration file data.
ApplicationContext applicationContext = new FileSystemXmlApplicationContext(“Spring-Config.xml”);