0% found this document useful (0 votes)
1 views17 pages

Unit-5 Spring Framework

The Spring Framework is a lightweight Java framework designed for building enterprise applications, offering features like Dependency Injection (DI), Aspect-Oriented Programming (AOP), and a modular architecture. It simplifies application development by providing transaction management, MVC support, and easy integration with other frameworks. Key components include the IoC container, which manages bean lifecycle and dependencies, and various modules for data access, web applications, and security.

Uploaded by

hackersinghss009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views17 pages

Unit-5 Spring Framework

The Spring Framework is a lightweight Java framework designed for building enterprise applications, offering features like Dependency Injection (DI), Aspect-Oriented Programming (AOP), and a modular architecture. It simplifies application development by providing transaction management, MVC support, and easy integration with other frameworks. Key components include the IoC container, which manages bean lifecycle and dependencies, and various modules for data access, web applications, and security.

Uploaded by

hackersinghss009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Spring Framework (Unit-5)

Introduction to Spring Framework


 What is Spring Framework?

The Spring Framework is a powerful, lightweight, and widely used Java framework for building
enterprise applications. It provides a comprehensive programming and configuration model for Java-
based applications, making development faster, scalable, and maintainable.

Before Enterprise Java Beans (EJB), JavaBeans were used for developing Web applications, but they
lacked essential services like transaction management and security. EJB was introduced to address
this by offering services for enterprise application development. However, it was complex, requiring
developers to create Home and Remote interfaces and implement lifecycle methods.

Spring Framework emerged as a solution to these complications. It simplifies enterprise application


development by using techniques like Aspect-Oriented Programming (AOP), Plain Old Java Objects
(POJO), and Dependency Injection (DI). Spring is an open-source, lightweight framework that
enables Java EE developers to build scalable and reliable applications, offering simpler alternatives to
traditional Java APIs like JDBC, JSP, and Servlets.

 Advantages of Spring Framework:

1. Light weight:
Spring framework is light weight framework because of its POJO model implementation.
2. Non-invasive approach:
As we know that struts forces programmer to extend Action Class but spring framework
doesn’t force a programmer to extend class or implement interface given by Spring API.
3. Loose Coupling:
Because of dependency injection concept, spring objects are loosely coupled.
4. Modular fashion:
Spring framework is designed in modular fashion. A programmer can use only needed
modules and ignore the rest.
5. Easy Testing:
Dependency injection and POJO model makes easy to test an application.
6. Transaction management interface:
Spring framework provides transaction management interface for transaction management.
7. No need of application server:
Struts or EJB application require application server to run but spring application doesn’t need
an application server.
8. MVC framework:
Spring framework is a great alternative to web MVC frameworks like Struts.

 Key Features of Spring Framework

The key features of Spring Framework are listed below:


 Dependency Injection: Dependency Injection is a design pattern where the Spring container
automatically provides the required dependencies to a class, instead of the class creating them
itself. This promotes loose coupling, easier testing, and better maintainability by decoupling the
object creation and usage.
 Aspect-Oriented Programming (AOP): AOP allows developers to separate cross-cutting
concerns (such as logging, security, and transaction management) from the business logic.

1|Page
Spring Framework (Unit-5)

 Transaction Management: Spring provides a consistent abstraction for managing transactions


across various databases and message services.
 Spring MVC: It is a powerful framework for building web applications that follow the Model-
View-Controller pattern.
 Spring Security: Spring provides security features like authentication, authorization, and more.
 Spring Data: Spring Data is a part of the Spring Framework that simplifies database access by
providing easy-to-use abstractions for working with relational and non-relational databases.
 Spring Batch: Spring Batch is a framework in Spring for handling large-scale batch processing,
such as reading, processing, and writing data in bulk.
 Integration with Other Frameworks: Spring integrates seamlessly with other technologies like
Hibernate, JPA, JMS, and more, making it versatile for various enterprise applications.

Spring framework architecture Diagram:

 1. Test:
Spring test module provides the supports for testing of spring components with JUnit or TestNG
frameworks.

 2. Core Container:
Spring core container contains the following:
a. Core: Core module provides the fundamental features of spring framework like IoC and DI.
b. Bean: Bean module provides the BeanFactory.
c. Context: Context module provides a way to access any object. ApplicationContext interface is the
main part of Context module.
d. Expression language: Expression language module provides a way to manipulate objects at runtime.

 3. Data Access/Integration contains the following:


a. JDBC: JDBC modules provides a JDBC-abstraction layer.
b. ORM: ORM provides integration layers for object-relational mapping APIs like JPA, and Hibernate

2|Page
Spring Framework (Unit-5)

etc.
c. OXM: OXM module provides an abstraction layer for Object/XML mapping APIs like JAXB, Castor
and XMLBeans etc.
d. JMS: JMS module provides feature of message processing.
e. Transaction: Transaction module provides the facility of transaction management for classes like
POJOs etc.

 4. Web:
Web module consist of Web, Web-Servlet, Web-Struts, Web-Socket and Web-Portlet which provides
the facility of creating web applications.

 5. AOP:
AOP module provides aspect-oriented programming implementation which provides the facility to
define method-interceptors.

 6. Instrumentation:
Instrumentation module provides class instrumentation support and class loader implementations

Spring IoC container types


Spring IoC container is responsible for create, wire, configure and
manage objects during their complete life cycle. It uses
configuration metadata for create, configure and manage objects.
Configuration metadata can be represented by spring configuration
xml file or annotations.

Types of Spring IoC container:


1. BeanFactory
2. ApplicationContext

 BeanFactory:
BeanFactory org.springframework.beans.factory. BeanFactory is the interface and XmlBeanFactory is
an implementation class of it. It is a simple container which provides the basic support for dependency
injection.

Syntax to use BeanFactory:


Resource resource = new ClassPathResource(“spring configuration file”);
BeanFactory beanFactory = new XmlBeanFactory(resource);

 ApplicationContext:
ApplicationContext org.springframework.context. ApplicationContext is the interface and
ClassPathXmlApplicationContext is an implementation class of it. ApplicationContext container
includes all functionality of the BeanFactory container with some extra functionality like
internationalization, event listeners etc.

Syntax to use ApplicationContext:


ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("spring configuration file");
Note: As ApplicationContext provides extra functionality including all given by BeanFactory it is
better to use ApplicationContext container.

3|Page
Spring Framework (Unit-5)

Spring bean
A spring bean represents an object that is created, configured and managed by spring container. A spring
bean is created by configuration metadata passed to the spring container which tells the container about
bean creation, bean lifecycle and bean dependencies.

 Spring bean properties:

Bean Properties Description


1. class It is mandatory and specify the bean class which is used to
create the bean.
2. name It specifies the bean unique identifier.
3. scope It specifies the scope of the objects created from a particular
bean definition.
4. constructor-arg It is used to inject the dependencies.
5. properties It is used to inject the dependencies.
6. autowiring mode It is used to inject the dependencies.
7. lazy-initialization It tells the IoC container to create a bean instance when it is
mode first requested, rather than at startup.
8. initialization It is a callback method to be called just after all necessary
method properties on the bean have been set by the container.
9. destruction It is a callback to be called when the container containing
method the bean is destroyed.

 Syntax using XML based configuration file:


<bean id="..." class="..." lazy-init="true">
//bean configuration
</bean>

Sample of XML-based configuration file with different bean definitions –


<?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-3.0.xsd">

<!-- A simple bean definition -->


<bean id = "..." class = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- A bean definition with lazy init set on -->


<bean id = "..." class = "..." lazy-init = "true">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- A bean definition with initialization method -->


<bean id = "..." class = "..." init-method = "...">
<!-- collaborators and configuration for this bean go here -->

4|Page
Spring Framework (Unit-5)

</bean>

<!-- A bean definition with destruction method -->


<bean id = "..." class = "..." destroy-method = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>

<!-- more bean definitions go here -->

</beans>

Spring bean scopes


As we discussed that spring container is responsible for creating and managing bean object. Spring
provides the facility to return the same instance or a new instance each time when one is needed. It
depends upon the bean scope.

 Spring framework bean scopes:


Bean Scope Description
1. singleton It scopes the bean definition to a single instance per spring
container. It is the default scope. Spring container keeps it into
cache and returns the same instance each time a request for that
particular bean is made.
2. prototype It scopes a single bean definition to have new bean instance each
time a request for that particular bean is made.
3. request It scopes a bean definition to an HTTP request.
4. session It scopes a bean definition to an HTTP session.
5. global- It scopes a bean definition to a global HTTP session.
session

The singleton scope


If a scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined
by that bean definition. This single instance is stored in a cache of such singleton beans, and all
subsequent requests and references for that named bean return the cached object.
The default scope is always singleton. However, when you need one and only one instance of a bean,
you can set the scope property to singleton in the bean configuration file, as shown in the following code
snippet −
<!-- A bean definition with singleton scope -->
<bean id = "..." class = "..." scope = "singleton">
<!-- collaborators and configuration for this bean go here -->

 The prototype scope


If the scope is set to prototype, the Spring IoC container creates a new bean instance of the object every
time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans
and the singleton scope for stateless beans.

To define a prototype scope, you can set the scope property to prototype in the bean configuration file,
as shown in the following code snippet −
<!-- A bean definition with prototype scope -->
<bean id = "..." class = "..." scope = "prototype">

5|Page
Spring Framework (Unit-5)

<!-- collaborators and configuration for this bean go here -->


</bean>

Bean Life Cycle in Java Spring


The lifecycle of a bean in Spring refers to the sequence of events that occur from the moment a bean is
instantiated until it is destroyed. Bean life cycle is managed by the spring container.

 Bean Life Cycle Phases


The lifecycle of a Spring bean consists of the
following phases, which are listed below
 Container Started: The Spring IoC
container is initialized.
 Bean Instantiated: The container creates an
instance of the bean.
 Dependencies Injected: The container
injects the dependencies into the bean.
 Custom init() method: If the bean
implements InitializingBean or has a custom
initialization method specified via
@PostConstruct or init-method.
 Bean is ready: The bean is now fully
initialized and ready to be used.
 Custom utility method: This could be any
custom method you have defined in your
bean.
 Custom destroy() method: If the bean
implements DisposableBean or has a custom
destruction method specified via
@PreDestroy or destroy-method, it is called
when the container is shutting down.

Spring hello world example in eclipse


Let us create spring hello world example by following below steps:
1. Download spring jar files and add into project class path. Or use the maven, see our Maven Eclipse
Spring example.
2. Create java class (bean).
3. Create spring configuration file which contains all bean configurations.
4. Create spring test class.
5. Load spring configuration file into Resource Interface object.
Syntax: Resource resource = new ClassPathResource(“spring configuration file”);
6. Create BeanFactory (Spring IOC container) object by reading spring configuration file through
resource object.
Syntax: BeanFactory beanFactory = new XmlBeanFactory(resource);
7. Get bean object from beanFactory (spring ioc container) by passing beanId.
TestBean testBean = beanFactory.getBean(“testBeanId″);

6|Page
Spring Framework (Unit-5)

Note:
1. We can also use ApplicationContext object for getting bean object as:
Synyax:
ApplicationContext context =
new ClassPathXmlApplicationContext("spring configuration file");
TestBean testBean = (TestBean) context.getBean("testBeanId");
2. Spring IOC container is responsible for creating bean objects and dependency injection.
3. Spring uses singleton design pattern for beans, so every spring bean is singleton class by default.

 Example:

HelloWorld.java
package com.w3schools.business;
public class HelloWorld {
private String userName;

public void setUserName(String userName) {


this.userName = userName;
}
public void sayHello(){
System.out.println("Hello: " + userName);
}
}

applicationContext.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-3.0.xsd">

<bean id="helloWorld" class="com.w3schools.business.HelloWorld">


<property name="userName" value="jai"/>
</bean>

</beans>

Test.java
package com.w3schools.business;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.sayHello();
}
}
Output:
Hello: jai
Spring - Inversion of Control with Example
7|Page
Spring Framework (Unit-5)

Spring IoC (Inversion of Control) Container is the core of the Spring Framework. It creates objects
(beans), configures them, injects dependencies, and manages their life cycles. The container uses
Dependency Injection (DI) to manage application components. It retrieves object configuration from
XML files, Java-based configuration, annotations, or POJOs. Since the Spring IoC container, not the
developer, controls the object lifecycle and dependency management, this concept is called Inversion of
Control (IoC).

 Spring - BeanFactory
Beans are Java objects that are configured at run-time by Spring IoC Container. BeanFactory represents
a basic IoC container which is a parent interface of ApplicationContext. BeanFactory uses Beans and
their dependencies metadata to create and configure them at run-time. BeanFactory loads the bean
definitions and dependency amongst the beans based on a configuration file (XML) or the beans can
be directly returned when required using Java Configuration. There are other types of configuration
files like LDAP, RDMS, properties files, etc. BeanFactory does not support Annotation-based
configuration whereas ApplicationContext does.

Some of the methods of Bean Factory before landing up on implementation which are shown below in
tabular format:

Method Description
containsBean(String name) Does this bean factory contain a bean definition or externally
registered singleton instance with the given name?
getBean(String name) Return an instance, which may be shared or independent, of the
specified bean.
getBean(String name, Class<T> Return an instance, which may be shared or independent, of the
requiredType) specified bean.
getBean(String name, Object... args) Return an instance, which may be shared or independent, of the
specified bean.
getType(String name) Determine the type of the bean with the given name.
isSingleton(String name) Is this bean a shared singleton? That is, will
getBean(java.lang.String) always return the same instance?
isTypeMatch(String name, Class<?> Check whether the bean with the given name matches the
typeToMatch) specified type.

Procedure:
 First, create a Spring project using start.spring.io.
 Create a POJO class.
 Configure the Student bean in the bean-factory-demo.xml file.
 Then write it to application class.

Step-by-Step Implementation to Configure Bean Factory in spring

Here is the content of HelloWorld.java file –


package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){

8|Page
Spring Framework (Unit-5)

System.out.println("Your Message : " + message);


}
}

Following is the content of the second file MainApp.java


package com.tutorialspoint;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class MainApp {
public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml"));
HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
obj.getMessage();
}
}

Following is the content of the bean configuration file Beans.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-3.0.xsd">

<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">


<property name = "message" value = "Hello World!"/>
</bean>
</beans>

 Spring - ApplicationContext
ApplicationContext is the sub-interface of BeanFactory. It is used when we are creating an
enterprise-level application or web application. ApplicationContext is the superset of BeanFactory,
whatever features provided by BeanFactory are also provided by ApplicationContext.

ApplicationContext Features
ApplicationContext provides basic features in addition to enterprise-specific functionalities which are
as follows:
 Publishing events to registered listeners by resolving property files.
 Methods for accessing application components.
 Supports Internationalization.
 Loading File resources in a generic fashion.

9|Page
Spring Framework (Unit-5)

Step-by-Step Implementation to Configure ApplicationContext in spring


Example
Here is the content of HelloWorld.java file −
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}

Following is the content of the second file MainApp.java –


package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext
("C:/Users/ZARA/workspace/HelloSpring/src/Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
}
}

Following is the content of the bean configuration file Beans.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-3.0.xsd">

<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">


<property name = "message" value = "Hello World!"/>
</bean>
</beans>

10 | P a g e
Spring Framework (Unit-5)

Difference between BeanFactory and ApplicationContext


Below is the difference table of Spring BeanFactory and ApplicationContext.
Feature BeanFactory ApplicationContext
Definition Fundamental container providing Advanced container extending
basic functionality for managing BeanFactory with additional
beans. features.
Usage Suitable for building standalone Suitable for building web
applications. applications, integrating with AOP
modules, ORM, and distributed
applications.
Bean Scopes Supports only Singleton and Supports all types of bean scopes,
Supported Prototype bean scopes. including Singleton, Prototype,
Request, Session, etc.
Annotation Support Does not support annotations; Supports annotation-based
requires configuration in XML configuration for bean autowiring.
files.
Internationalization Does not provide Extends MessageSource interface
internationalization (i18n) to provide internationalization
functionality. (i18n) functionality.
Event Handling Does not support event publication. Supports event handling via the
ApplicationEvent class and
ApplicationListener interface.
Bean Post Processing Requires manual registration of Automatically registers
BeanPostProcessors and BeanFactoryPostProcessor and
BeanFactoryPostProcessors. BeanPostProcessor at startup.
Initialization Creates bean objects on demand Loads all beans and creates objects
using lazy initialization. at startup using eager initialization.
Resource Usage Provides basic features requiring Provides basic and advanced
less memory, suitable for memory- features, suitable for enterprise
critical standalone applications. applications, requiring more
memory.

Spring dependency injection tutorial


 Injection:
Injection is a process of passing the dependency to a dependent object.

 Dependency Injection (DI):


Dependency Injection (DI) is a design pattern that implements inversion of control principle for
resolving dependencies. It allows a programmer to remove hard coded dependencies so that the
application becomes loosely coupled and extendable.

 Let us discuss object dependency with below example:


public class Student {
private Address address;

public Student() {
address = new Address();
}
}

11 | P a g e
Spring Framework (Unit-5)

In above example Student class requires an Address object and it is responsible for initializing and using
the Address object. If Address class constructor is changed in future then we have to make changes in
Student class also. This approach makes tight coupling between Student and Address objects. We can
resolve this problem using dependency injection design pattern. i.e. Address object will be implemented
independently and will be provided to Student when Student is instantiated by using constructor-based
or setter-based dependency injection.

Types of dependency Injection:


1. Constructor-based Dependency Injection.
2. Setter-based Dependency Injection.

 Spring constructor based injection


Constructor based dependency injection is a process of passing the dependency to a dependent object
via a constructor.

Note:
1. For primitive data types use element and for dependent objects use
<ref bean="beanId"/>
2. Index attribute is used to specify the index of constructor arguments.

Example Explanation:
We have created two beans “Student” and “Address”. Student class requires an Address class object. In
spring configuration file we define Address bean and pass this as an argument in Student class using
constructor-arg element.
Example:
Student.java
package com.w3schools.business;
public class Student {
private String name;
private String rollNo;
private String className;
private Address address;

public Student(Address address){


this.address = address;
}

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getClassName() {
return className;
}

12 | P a g e
Spring Framework (Unit-5)

public void setClassName(String className) {


this.className = className;
}
public Address getAddress() {
return address;
}

}
Address.java
package com.w3schools.business;
public class Address {
private String addLine;
private String city;
private String state;
private String country;

public String getAddLine() {


return addLine;
}
public void setAddLine(String addLine) {
this.addLine = addLine;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}

applicationContext.java
<?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-3.0.xsd">

<bean id="student" class="com.w3schools.business.Student">


<property name="name" value="Jai"/>

13 | P a g e
Spring Framework (Unit-5)

<property name="rollNo" value="MCA/07/06"/>


<property name="className" value="MCA"/>
<constructor-arg ref="address"/>
</bean>

<bean id="address" class="com.w3schools.business.Address">


<property name="addLine" value="Test address"/>
<property name="city" value="Gurgaon"/>
<property name="state" value="Haryana"/>
<property name="country" value="India"/>
</bean>

</beans>

Test.java
package com.w3schools.business;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//Get ApplicationContext using spring configuration file.
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");

//Get Student bean object from ApplicationContext instance.


Student student = (Student) context.getBean("student");

//Process Student Object.


System.out.println("Student info: ");
System.out.println("Name: " + student.getName());
System.out.println("RollNo: " + student.getRollNo());
System.out.println("Class: " + student.getClassName());

//Get Address from Student Object.


Address studentAddress = student.getAddress();
System.out.println("Student Address: ");
System.out.println("Address Line: " + studentAddress.getAddLine());
System.out.println("City: " + studentAddress.getCity());
System.out.println("State: " + studentAddress.getState());
System.out.println("Country: " + studentAddress.getCountry());
}
}
Output:
Student info:
Name: Jai
RollNo: MCA/07/06
Class: MCA
Student Address:
Address Line: Test address
City: Gurgaon
State: Haryana
Country: India

14 | P a g e
Spring Framework (Unit-5)

 Setter based dependency injection


Setter based dependency injection is a process of passing the dependency to a dependent object via a
setter method.

Note:
1. For primitive data types use element and for dependent objects use
<ref bean="beanId"/>
2. Index attribute is used to specify the index of constructor arguments.

Example Explanation:
We have created two beans “Student” and “Address”. Student class requires an Address class object. In
spring configuration file we define Address bean and pass this as an argument in Student class using
parameter element.

Example:
Student.java
package com.w3schools.business;
public class Student {
private String name;
private String rollNo;
private String className;
private Address address;

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}

Address.java
package com.w3schools.business;
public class Address {

15 | P a g e
Spring Framework (Unit-5)

private String addLine;


private String city;
private String state;
private String country;

public String getAddLine() {


return addLine;
}
public void setAddLine(String addLine) {
this.addLine = addLine;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
applicationContext.java
<?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-3.0.xsd">

<bean id="student" class="com.w3schools.business.Student">


<property name="name" value="Jai"/>
<property name="rollNo" value="MCA/07/06"/>
<property name="className" value="MCA"/>
<property name="address" ref="address"/>
</bean>

<bean id="address" class="com.w3schools.business.Address">


<property name="addLine" value="Test address"/>
<property name="city" value="Gurgaon"/>
<property name="state" value="Haryana"/>
<property name="country" value="India"/>
</bean>

</beans>
Test.java

16 | P a g e
Spring Framework (Unit-5)

package com.w3schools.business;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {


public static void main(String[] args) {
//Get ApplicationContext using spring configuration file.
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");

//Get Student bean object from ApplicationContext instance.


Student student = (Student) context.getBean("student");

//Process Student Object.


System.out.println("Student info: ");
System.out.println("Name: " + student.getName());
System.out.println("RollNo: " + student.getRollNo());
System.out.println("Class: " + student.getClassName());

//Get Address from Student Object.


Address studentAddress = student.getAddress();

//Process Address Object.


System.out.println("Student Address: ");
System.out.println("Address Line: " + studentAddress.getAddLine());
System.out.println("City: " + studentAddress.getCity());
System.out.println("State: " + studentAddress.getState());
System.out.println("Country: " + studentAddress.getCountry());
}
}
Output:
Student info:
Name: Jai
RollNo: MCA/07/06
Class: MCA
Student Address:
Address Line: Test address
City: Gurgaon
State: Haryana
Country: India

17 | P a g e

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy