One
One
// POJO class
public class Student {
// Member variables
private String name;
private String age;
// Constructor 1
public Student() {
}
// Constructor 2
public Student(String name, String age) {
this.name = name;
this.age = age;
}
// Main class
public class DemoApplication {
// Main driver method
public static void main(String[] args) {
System.out.println(student);
}
}
op: Student{name='Tina', age='21'}
***************************
Spring – ApplicationContext
======
Spring IoC container
It is responsible for instantiating, wiring, configuring, and managing the entire
life cycle of beans or objects.
BeanFactory and ApplicationContext represent the Spring IoC Containers.
ApplicationContext is the sub-interface of BeanFactory.
Used when we are creating an enterprise-level application or web application.
ApplicationContext is the superset of BeanFactory.
ApplicationContext Features
====
Publishing events to registered listeners by resolving property files.
Methods for accessing application components.
Supports Internationalization.
Loading File resources in a generic fashion.
1 AnnotationConfigApplicationContext container
====
AnnotationConfigApplicationContext class was introduced in Spring 3.0
It accepts classes annotated with @Configuration, @Component, and JSR-330 compliant
classes.
The constructor of AnnotationConfigApplicationContext accepts one or more classes.
For example,
in the below declaration, two Configuration classes Appconfig and AppConfig1 are
passed as arguments to the constructor.
The beans defined in later classes will override the same type and name beans in
earlier classes when passed as arguments.
For example, AppConfig and AppConfig1 have the same bean declaration. The bean
defined in AppConfig1 overrides the bean
in AppConfig.
Syntax: Declaration
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class, AppConfig1.class);
// Servlet container
// Servlet configuration
}
}
Container 3: XmlWebApplicationContext
==========
Spring MVC Web-based application can be configured completely using XML or Java
code.
Configuring this container is similar to the AnnotationConfigWebApplicationContext
container,
which implies we can configure it in web.xml or using java code.
--
// Class
// Implementing WebApplicationInitializer
public class MyXmlWebApplicationInitializer implements WebApplicationInitializer {
// Servlet container
public void onStartup(ServletContext container) throws ServletException {
XmlWebApplicationContext context = new XmlWebApplicationContext();
context.setConfigLocation("/WEB-INF/spring/applicationContext.xml");
context.setServletContext(container);
// Servlet configuration
}
}
Container 4: FileSystemXmlApplicationContext
==========
FileSystemXmlApplicationContext is used to load XML-based Spring Configuration
files from the file system or from URL.
We can get the application context using Java code.
It is useful for standalone environments and test harnesses.
Syntax :
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationcontext/student-bean-config.xml");
StudentService studentService = context.getBean("studentService",
StudentService.class);
----------
Implementation:
// Class
public class AppConfig {
@Bean
// Method
public Student student() {
// member variables
private int id;
private String name;
// Constructor 1
public Student() {}
// Constructor 2
public Student(int id, String name) {
this.id = id;
this.name = name;
}
// SpringApplication.run(DemoApplication.class, args);
// Creating its object
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
Student student = context.getBean(Student.class);
Static Factory Method – It is used to return the instance of its own class.
Static factory methods are used for Singleton Design Pattern.
Static Factory Method – It is used to return the runtime instance of another class.
Non-Static Factory Method – It is used to return the runtime instance of another
class.
------------
Step 1: Create Geeks Class
----
public class Geeks {
// private constructor
private Geeks() {}
Implementation
The map will have both key and value as non-strings. Key will be Employee which has
the following fields:
Name
Employee ID
Department
Value will be Address which has the following parameters:
House No.
Pincode
State
Country
------- Company.java
// Java Program to Illustrate Company Class
package com.geeksforgeeks.org;
// Importing required classes
import com.geeksforgeeks.org.Address;
import com.geeksforgeeks.org.Employee;
import java.util.*;
import java.util.Map.Entry;
// Print statement
System.out.println(
"Employee Data ->"
+ entry.getKey().toString() + " Address ->"
+ entry.getValue().toString());
}
}
}
----------
// Java Program to Illustrate Employee Class
package com.geeksforgeeks.org;
import com.geeksforgeeks.org.Address;
public class Employee {
private String name;
private String employeeID;
private String department;
c.display();
}
}
***********************************
Spring – Constructor Injection with Map
----------------- // Java Program to illustrate Company Class
package com.geeksforgeeks.org;
System.out.println(
"Employee Id ->" + entry.getKey() + ","
+ " Department->" + entry.getValue());
}
}
}
----------
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="company" class="com.geeksforgeeks.org.Company">
<constructor-arg>
<map>
<entry key="101" value="Software development"></entry>
<entry key="102" value="Software testing"></entry>
<entry key="103" value="Security"></entry>
</map>
</constructor-arg>
</bean>
</beans>
--------- // Java Program to Illustrate Application Class
package com.geeksforgeeks.org;
public class Test {
public static void main(String[] args)
{
Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Employee c = (Employee)factory.getBean("company");
c.display();
}
}
-------
*****************************************************************
Spring – Setter Injection with Dependent Object
================================== // Java Program to Illustrate Employee Class
package com.geeksforgeeks.org;
class Employee {
private String name;
private String employeeID;
private String department;
private Address address;
class Address {
private String houseNo;
private String pincode;
private String state;
private String country;
public Address(String houseNo, String pincode, String state, String country)
{
super();
this.houseNo = houseNo;
this.pincode = pincode;
this.state = state;
this.country = country;
}
package com.geeksforgeeks.org;
import com.geeksforgeeks.org.Address;
// Class
public class Employee {
private String name;
private String employeeID;
private String department;
// Parameterised constructor
public Employee(String name, String employeeID,
String department, Address address)
{
// this keyword refers to current instance itself
this.name = name;
this.employeeID = employeeID;
this.department = department;
this.address = (Address)address;
}
// Method
public void display()
{
System.out.println("Name: " + name);
System.out.println("Employee ID: " + employeeID);
System.out.println("Department: " + department);
System.out.println("Address: " + address);
}
}
-----// Java Program to Illustrate Address Class
package com.geeksforgeeks.org;
// Method
public String toString()
{
return "[" + houseNo + "," + pincode + "," + state
+ "," + country + "]";
}
}
--------
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>
-----
// Java Program to Illustrate Application Class
package com.geeksforgeeks.org;
// Main(Application) class
public class Test {
package com.geeksforgeeks.org;
import java.util.*;
class Company {
private String companyName;
private List<String> employees;
package com.geeksforgeeks.org;
package com.geeksforgeeks.org;
// Class
class Employee {
// Method
public String getName() { return name; }
// Setter
public void setName(String name) { this.name = name; }
// Getter
public String getEmployeeID() { return employeeID; }
// Setter
public void setEmployeeID(String employeeID)
{
this.employeeID = employeeID;
}
// Getter
public String getDepartment() { return department; }
// Setter
public void setDepartment(String department)
{
this.department = department;
}
// Method
// Overriding toString() method of String class
@Override public String toString()
{
return ("[Name: " + name
+ ", Employee Id: " + employeeID
+ ", Department: " + department + "]");
}
}
------------
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http:www.springframework.org/schema/beans/spring-beans-3.0.xsd">
package com.geeksforgeeks.org;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Main {
public static void main(String[] args) {
Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Company c = (Company)factory.getBean("company");
c.display();
}
}
********************
Spring – Constructor Injection with Collection
===============================================
package com.geeksforgeeks.org;
import com.geeksforgeeks.org.IGeek;
import java.util.List;
public class Employee {
private String name;
private String employeeID;
private String department;
private List<String> address;
public Employee(List<String> address) {
this.address = (List<String>)address;
}
</beans>
--------
package com.geeksforgeeks.org;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
// Class
public class Student {
// Attributes
private int id;
private MathCheat mathCheat;
// Method
public void cheating()
{
System.out.println("My ID is: " + id);
mathCheat.mathCheating();
}
}
-------
// Java Program to Illustrate MathCheat File
// Class
public class MathCheat {
// Method
public void mathCheating()
{
// Print statement
System.out.println(
"And I Have Stated Math Cheating");
}
}
-------
// Java Program to Illustrate Student File
// Class
public class Student {
// Attributes
private int id;
private MathCheat mathCheat;
// Setter
public void setId(int id) { this.id = id; }
// Setter
public void setMathCheat(MathCheat mathCheat)
{
this.mathCheat = mathCheat;
}
// Method
public void cheating()
{
// Print statement
System.out.println("My ID is: " + id);
mathCheat.mathCheating();
}
}
---------
<?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">
</beans>
--------- // Java Program to Illustrate Main File Implementing Spring IoC
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");
Student student = context.getBean("student", Student.class);
student.cheating();
}
}
-------- Another Approach (Right Approach)
<?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="mathCheatObjectValue" class="MathCheat"></bean>
<bean id="student" class="Student">
<property name="id" value="101"/>
<property name="mathCheat" ref="mathCheatObjectValue"/>
</bean>
</beans>
******************
Spring – Injecting Literal Values By Setter Injection
--------
public class Student {
private int id;
private String studentName;
public void setId(int id) { this.id = id; }
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public void displayInfo(){
System.out.println("Student Name is " + studentName + " and Roll
Number is " + id);
}
}
---------
<?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">
</beans>
----------
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
// Class
public class Student {
// Method
public void displayInfo()
{
// Printing name and corresponding
// roll number of Student
System.out.println("Student Name is " + studentName
+ " and Roll Number is " + id);
}
}
----------------
<?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="studentAmiya" class="Student">
<constructor-arg name="id" value="101"/>
<constructor-arg name="studentName" value="Amiya Rout"/>
</bean>
<bean id="studentAsish" class="Student">
<constructor-arg name="id" value="102"/>
<constructor-arg name="studentName" value="Asish Rout"/>
</bean>
</beans>
---------
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Exam {
public static void main(String[] args) {
// Implementing Spring IoC using ApplicationContext
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");
Student amiya = context.getBean("studentAmiya", Student.class);
amiya.displayInfo();
asish.displayInfo();
}
}
********************
Bean life cycle in Java Spring
=============
Ways to implement the life cycle of a bean
---------
By XML: In this approach, in order to avail custom init() and destroy() methods
for a bean we have to register these two methods inside the Spring XML
configuration file while defining a bean.
------// Java program to create a bean
package beans;
public class HelloWorld {
// This method executes automatically as the bean is instantiated
public void init() throws Exception
{
System.out.println(
"Bean HelloWorld has been " + "instantiated and I'm "+ "the
init() method");
}
package test;
import beans.HelloWorld;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args) throws Exception
{
// Loading the Spring XML configuration file into the spring container
and
it will create the instance of the bean as it loads into container
ConfigurableApplicationContext cap= new
ClassPathXmlApplicationContext("resources/spring.xml");
// It will close the spring container and as a result invokes the
destroy() method
cap.close();
}
}
********************
Different Methods to Create a Spring Bean
=================
Creating Bean Inside an XML Configuration File (beans.xml)
Using @Component Annotation
Using @Bean Annotation
------- Method 1: Creating Bean Inside an XML Configuration File (beans.xml)
// Java Program to Illustrate Student Class
public class Student {
private int id;
private String studentName;
public void displayInfo()
{
System.out.println("Student Name is " + studentName + " and Roll
Number is " + id);
}
}
-------
<?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>
</beans>
-*-*-*-*-*-*-*--*-*
Method 2: Using @Component Annotation
---------
// Java Program to Illustrate College Class
package ComponentAnnotation;
public class College {
public void test(){
System.out.println("Test College Method");
}
}
---- // Java Program to Illustrate College Class
package ComponentAnnotation;
import org.springframework.stereotype.Component;
@Component("collegeBean")
public class College {
public void test(){
System.out.println("Test College Method");
}
}
-*--*-*--*-*-*-*-*-*-
Method 3: Using @Bean Annotation
---------
package BeanAnnotation;
import org.springframework.stereotype.Component;
public class College {
public void test(){
System.out.println("Test College Method");
}
}
-----
package ComponentAnnotation;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CollegeConfig {
}
-----
// Java Program to Illustrate Configuration in College Class
package BeanAnnotation;
@Configuration
public class CollegeConfig {
// Using Bean annotation to create College class Bean
@Bean
public College collegeBean(){ // Here the method name is the bean
id/bean name
return new College();
}
}
********************
important features of the Spring framework
==========
IoC container
Data Access Framework
Spring MVC
Transaction Management
Spring Web Services
JDBC abstraction layer
Spring TestContext framework
*******************************
Spring – Autowiring
=========
class City {
private int id;
private String name;
private State s;
public int getID() { return id; }
public void setId(int eid) { this.id = eid; }
public String getName() { return name; }
public void setName(String st) { this.name = st; }
public State getState() { return s; }
@Autowired public void setState(State sta)
{
this.s = sta;
}
public void showCityDetails()
{
System.out.println("City Id : " + id);
System.out.println("City Name : " + name);
System.out.println("State : " + s.getName());
}
}
----------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="state" class="sample.State">
<property name="name" value="UP" />
</bean>
<bean id="city" class="sample.City" autowire="byName"></bean>
</beans>
-------
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
City cty = context.getBean("city", City.class);
cty.setId(01);
cty.setName("Varanasi");
State st = context.getBean("state", State.class);
st.setName("UP");
cty.setState(st);
cty.showCityDetails();
}
}
----------
Advantage: It requires less code because we don’t need to write the code to inject
the dependency explicitly.
Disadvantage: No control of the programmer and It can’t be used for primitive and
string values.
*****************************
Singleton and Prototype Bean Scopes in Java Spring
================
Singleton: Only one instance will be created for a single bean definition per
Spring IoC container and the same object will be shared for each request made for
that bean.
Prototype: A new instance will be created for a single bean definition every time a
request is made for that bean.
Request: A new instance will be created for a single bean definition every time an
HTTP request is made for that bean. But Only valid in the context of a web-aware
Spring ApplicationContext.
Session: Scopes a single bean definition to the lifecycle of an HTTP Session. But
Only valid in the context of a web-aware Spring ApplicationContext.
Global-Session: Scopes a single bean definition to the lifecycle of a global HTTP
Session. It is also only valid in the context of a web-aware Spring
ApplicationContext
------------------
Singleton Scope:
If the scope is a singleton, then only one instance of that bean will be
instantiated per Spring IoC container and the same instance will be shared for each
request.
------------
// Java program to illustrate a bean created in the spring framework
package bean;
public class HelloWorld {
public String name;
// Create a setter method to set the value passed by user
public void setName(String name){
this.name = name;
}
// Create a getter method so that the user can get the set value
public String getName()
{
return name;
}
}
------------
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!--configure the bean HelloWorld.java
and declare its scope-->
< bean
id = "hw"
class= "bean.HelloWorld"
scope = "singleton" / >
</beans>
---------------
// Java program to illustrate the client to perform the request to the defined bean
package driver;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import bean.HelloWorld;
// Client Class to request the above defined bean
public class Client {
public static void main(String[] args) {
// Load the Spring XML configuration file into IoC container
ApplicationContext ap= new
ClassPathXmlApplicationContext("resources/spring.xml");
// Get the "HelloWorld" bean object and call getName() method
HelloWorld Geeks1= (HelloWorld)ap.getBean("hw");
// Set the name
Geeks1.setName("Geeks1");
System.out.println("Hello object (hello1)"+ " Your name is: "+
Geeks1.getName());
// Get another "HelloWorld" bean object and call getName() method
HelloWorld Geeks2= (HelloWorld)ap.getBean("hw");
System.out.println("Hello object (hello2)"+ " Your name is: "+
Geeks2.getName());
// Now compare the references to see whether they are pointing to the
// same object or different object
System.out.println("'Geeks1' and 'Geeks2'"+ " are referring"+ "to the
same object: "
+ (Geeks1 == Geeks2));
// Print the address of both object Geeks1 and Geeks2
System.out.println("Address of object Geeks1: "+ Geeks1);
System.out.println("Address of object Geeks2: " + Geeks2);
}
}
*-*-*-*-*-*-*-*-*-
Prototype Scope:
If the scope is declared prototype, then spring IOC container will create a new
instance of that bean every time a request is made for that specific bean.
A request can be made to the bean instance either programmatically using getBean()
method or by XML for Dependency Injection of secondary type
---------
// Java program to illustrate a bean
// created in the spring framework
package bean;
public class HelloWorld {
public String name;