[go: up one dir, main page]

0% found this document useful (0 votes)
77 views41 pages

One

The document describes how to configure dependency injection in Spring. It explains setter dependency injection where dependencies are injected using setter methods, and constructor dependency injection where dependencies are injected through class constructors. Code examples are provided to illustrate both approaches.

Uploaded by

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

One

The document describes how to configure dependency injection in Spring. It explains setter dependency injection where dependencies are injected using setter methods, and constructor dependency injection where dependencies are injected through class constructors. Code examples are provided to illustrate both approaches.

Uploaded by

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

Procedure

1. Creating a Spring project using start.spring.io.


2. Creating a POJO class.
3. Configure the Student bean in the bean-factory-demo.xml file.
4. Writing it to application class.
================================================================
Step 1: Bean Definition: Create a Student POJO class.
----------
// Java Program where we are
// creating a POJO class

// 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;
}

// Method inside POJO class


@Override
public String toString() {

// Print student class attributes


return "Student{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}';
}
}
>>>>>>>>>>>
Step 2: XML Bean Configuration: Configure the Student bean in the bean-factory-
demo.xml file.
----------
<?xml version = "1.0" encoding="UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="student" class = "com.gfg.demo.domain.Student">


<constructor-arg name="name" value="Tina"/>
<constructor-arg name="age" value="21"/>
</bean>
</beans>
>>>>>>>>
Step 3: Main Class
-------------
// Application class
@SpringBootApplication

// Main class
public class DemoApplication {
// Main driver method
public static void main(String[] args) {

// Creating object in a spring container (Beans)


BeanFactory factory = new ClassPathXmlApplicationContext("bean-factory-
demo.xml");
Student student = (Student) factory.getBean("student");

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.

ApplicationContext Implementation Classes


======
1 AnnotationConfigApplicationContext container
2 AnnotationConfigWebApplicationContext
3 XmlWebApplicationContext
4 FileSystemXmlApplicationContext
5 ClassPathXmlApplicationContext

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);

application.properties ==> spring.main.allow-bean-definition-overriding=true


Container 2: AnnotationConfigWebApplicationContext
===
AnnotationConfigWebApplicationContext class was introduced in Spring 3.0.
It is similar to AnnotationConfigApplicationContext for a web environment.
It accepts classes annotated with @Configuration, @Component, and JSR-330 compliant
classes.
These classes can be registered via register() method or passing base packages to
scan() method.
Example
// Class
// Implementing WebApplicationInitializer
public class MyWebApplicationInitializer implements WebApplicationInitializer {

// Servlet container

public void onStartup(ServletContext container) throws ServletException {


AnnotationConfigWebApplicationContext context = new
AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
context.setServletContext(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:

Create a Spring Project using Spring Initializer.


Create Student class under com.gfg.demo.domain
Similarly, AppConfig class under com.gfg.demo.config packages.
The main application class at the root contains the creation of a container.
Lastly, the SpringApplication.run() method is provided by default in the main class
when the SpringBoot project is created.
--
Class 1: AppConfig class
@Configuration

// Class
public class AppConfig {

@Bean

// Method
public Student student() {

return new Student(1, "Geek");


}
}
--
Class 2: Student class
// Class
public class 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;
}

// Method of this class


// @Override
public String toString() {

return "Student{" + "id=" + id + ", name='" + name + '\'' + '}';


}
}
--
Step 3: Now the Main Application class at the root contains the creation of a
container.
// @SpringBootApplication
public class DemoApplication {

// Main driver method


public static void main(String[] args) {

// SpringApplication.run(DemoApplication.class, args);
// Creating its object
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
Student student = context.getBean(Student.class);

// Print and display


System.out.println(student);
}
}
--
Step 4: The SpringApplication.run() method is provided by default in the main class
when the SpringBoot project is created. It creates the container, creates beans,
manages dependency injection
and life cycle of those beans.
This is done using @SpringBootApplication annotation.
--
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
Student student = context.getBean(Student.class);
System.out.println(student);
}
***************
DI
===========
1 Setter Dependency Injection (SDI)
the DI will be injected with the help of setter and/or getter methods
set the DI as SDI in the bean, it is done through the bean-configuration file.
property to be set with the SDI is declared under the <property> tag in the bean-
config file.
Example: Let us say there is class GFG that uses SDI and sets the property geeks.
--
package com.geeksforgeeks.org;
import com.geeksforgeeks.org.IGeek;
public class GFG {
// The object of the interface IGeek
IGeek geek;
// Setter method for property geek
public void setGeek(IGeek geek) {
this.geek = geek;
}
}
--beanconfig.xml
<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-2.5.xsd">
<bean id="GFG" class="com.geeksforgeeks.org.GFG">
<property name="geek"> <ref bean="CsvGFG" /> </property>
</bean>
<bean id="CsvGFG" class="com.geeksforgeeks.org.impl.CsvGFG" />
<bean id="JsonGFG" class="com.geeksforgeeks.org.impl.JsonGFG" />
</beans>
--This injects the ‘CsvGFG’ bean into the ‘GFG’ object with the help of a setter
method (‘setGeek’)
--------------
Constructor Dependency Injection :
------------
DI will be injected with the help of contructors.
set the DI as CDI in bean, it is done through the bean-configuration file .
property to be set with the CDI is declared under the <constructor-arg>
--
package com.geeksforgeeks.org;
import com.geeksforgeeks.org.IGeek;
public class GFG {
// The object of the interface IGeek
IGeek geek;
// Constructor to set the CDI
GFG(IGeek geek) {
this.geek = geek;
}
}
---
<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-2.5.xsd">
<bean id="GFG" class="com.geeksforgeeks.org.GFG">
<constructor-arg>
<bean class="com.geeksforgeeks.org.impl.CsvGFG" />
</constructor-arg>
</bean>
<bean id="CsvGFG" class="com.geeksforgeeks.org.impl.CsvGFG" />
<bean id="JsonGFG" class="com.geeksforgeeks.org.impl.JsonGFG" />
</beans>
----- This injects the ‘CsvGFG’ bean into the ‘GFG’ object with the help of a
constructor.
-----------------
********************
Types of Factory Method
There are three types of factory methods:

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 {

// define a private static instance


public static final Geeks geeks = new Geeks();

// private constructor
private Geeks() {}

// this method will return the above instance


// which was created when the class loaded in the memory
public static Geeks getGeeks() {
return geeks;
}

// this method is used to check the dependency injection


public void geeksMessage() {
System.out.println("Welcome to geeksforgeeks. DI for static factory
method working good");
}
}
---
Step 2: Adding Dependencies
-----
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.geeksforgeeks</groupId>
<artifactId>DIFactoryMethods</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
</dependencies>
</project>
------------
Step 3: Bean Configuration
----------
<?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="geeksId" class="com.geeksforgeeks.model.Geeks" factory-
method="getGeeks">
</bean>
</beans>
-------
Step 4: Create Utility Class
-----// Java Program to Illustrate TestDIFactoryMethod Class
// Importing required classes
import com.geeksforgeeks.model.Geeks;
public class TestDIFactoryMethod {
public static void main(String[] args) {
AbstractApplicationContext context = new
ClassPathXmlApplicationContext("application-context.xml");
// Spring check the blueprint for Geeks bean
// from application-context.xml file and return it
Geeks geeksObj = (Geeks)context.getBean("geeksId");
// geeksObj contain the dependency of Geeks class
geeksObj.geeksMessage();
}
}
------------
------------------
B. Static Factory Method – Returning Instance of Another Class
-------- Step 1: Create An Interface
public interface GeeksCourses {
Public void getCourseDetail();
}
-------- Step 2: Create Dependent Classes
public class DSACourses implements GeeksCourses {
public void getCourseDetail(){
System.out.println("Data Structure & Algorithms");
}
------
public class JavaCourses implements GeeksCourses {
public void getCourseDetail()
{
System.out.println("Core Java Collections");
}
}
-------- Step 3: Create A Factory Class
Package com.geeksforgeeks.model;
public class CourseFactory {
// factory method returning instance to another class
public static GeeksCourses getCourses()
{
// Returning the instance of JavaCourses class
// One can also return the instance of DSACourses
return new JavaCourses();
}
}
-------- Step 4: Bean Configuration
<?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">
<!-- Note: You need to define your whole class path for your CourseFactory.java
class -->
<bean id="courseId" class="com.geeksforgeeks.model.CourseFactory"
factory-method="getCourses">
</bean>
</beans>
-----------------
// Java Program to Illustrate TestDIFactoryMethod Class
public class TestDIFactoryMethod {
public static void main(String[] args)
{
// from the class-path
AbstractApplicationContext context = new
ClassPathXmlApplicationContext("application-context.xml");
// Spring check the blueprint for GeeksCourses bean from application-
context.xml file and return it
GeeksCourses geeksCourses = (GeeksCourses)context.getBean("courseId");
// geeksCourses contain the dependency of GeeksCourses class
geeksCourses.getCourseDetail();
}
}
-------
----------
C. Non-Static Factory Method – Returning instance of another class
---------- Step 1: Create An Interface
// Java Program to Illustrate GeeksCourses Interface
public interface GeeksCourses
{
public void getCourseDetail();
}
---
// Java Program to illustrate DSACourses Class
public class DSACourses implements GeeksCourses {
public void getCourseDetail()
{
System.out.println("Data Structure & Algorithms");
}
}
----
// Java Program to Illustrate JavaCourses Class
public class JavaCourses implements GeeksCourses {
public void getCourseDetail()
{
System.out.println("Core Java Collections");
}
}
------
// Java Program to Illustrate CourseFactory Class
public class CourseFactory {
// Non-static factory method that returns
// the instance to another class
public GeeksCourses getCourses(){
// Returning the instance of JavaCourses class
// One can also return the instance of DSACourses
return new DSACourses();
}
}
-------
<?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">
<!-- Note: You need to define your whole class path for your CourseFactory.java
class -->
<bean id="courseFactory" class="com.geeksforgeeks.model.CourseFactory"></bean>
<bean id="courseId" class="com.geeksforgeeks.model.CourseFactory"
factory-method="getCourses" factory-bean="courseFactory">
</bean>
</beans>
----------
// Java Program to Illustrate TestDIFactoryMethod Class
public class TestDIFactoryMethod {
public static void main(String[] args)
{
// Reading the application-context file from the class-path
AbstractApplicationContext context = new
ClassPathXmlApplicationContext("application-context.xml");
// Spring check the blueprint for GeeksCourses bean from application-
context.xml file and return it
GeeksCourses geeksCourses = (GeeksCourses)context.getBean("courseId");
// geeksCourses contain the dependency of GeeksCourses class
geeksCourses.getCourseDetail();
}
}
***************************
Dependency Injection by Setter Method
=======================================
package com.spring;
public class Student {
private String studentName;
private String studentCourse;

public String getStudentName() {


return studentName;
}

public void setStudentName(String studentName) {


this.studentName = studentName;
}

public String getStudentCourse() {


return studentCourse;
}

public void setStudentCourse(String studentCourse) {


this.studentCourse = studentCourse;
}

@Override public String toString()


{
return "Student{"
+ "studentName=" + studentName +
", studentCourse=" + studentCourse + '}';
}
}
---------------------
<?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
https://www.springframework.org/schema/beans/spring-
beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-
context.xsd">
<bean class="com.springframework.Student" name="stud">
<property name="studentName">
<value> John </value>
<property/>
<property name="studentCourse">
<value> Spring Framework </value>
<property/>
</bean>
</beans>
-------------
package com.spring;
import java.io.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationCotenxt;
public class GFG {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationCotenxt("config.xml");
Student student= (Student)context.getBean("stud");
System.out.println(student);
}
}
Student{ studentName= John , studentCourse= Spring Framework }
*********************************************************************************
Spring – Setter Injection with Non-String Map
---------
Spring framework provides us facility of Setter injection using the following
Collections:
List Map Set

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;

public class Company {


// Class member variable
private Map<Employee, Address> employees;
// Method
public void display()
{
// Iterating over Map using for each loop
for (Map.Entry<Employee, Address> entry :
employees.entrySet()) {

// 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;

public Employee(String name, String employeeID, String department)


{
// This keyword refers to current instance itself
this.name = name;
this.employeeID = employeeID;
this.department = department;
}
// Overriding toString() method
public String toString()
{
return ("[" + name + "," + employeeID + ","
+ department + "]");
}
}
---------
// Java Program to Illustrate Address Class
public 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;
}
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">
<bean id="employee1" class="com.geeksforgeeks.org.Employee">
<property name="name" value="Sahil"></property>
<property name="employeeID" value="101"></property>
<property name="department" value="Game development"></property>
</bean>
<bean id="address1" class="com.geeksforgeeks.org.Address">
<property name="houseNo" value="2"></property>
<property name="pincode" value="110111"></property>
<property name="state" value="Bihar"></property>
<property name="country" value="India"></property>
</bean>
<bean id="company" class="com.geeksforgeeks.org.Company">
<map>
<entry key-ref="employee1" value-ref="address1"></entry>
</map>
</property>
</bean>
</beans>
------------
// Java Program to Illustrate Application Class
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;

public class Test {


public static void main(String[] args)
{
// Creating a class path resource
Resource resource = new ClassPathResource("applicationContext.xml");
// Creating an object of Beanfactory class
BeanFactory factory = new XmlBeanFactory(resource);
// Creating an object of Employee class
Company c = (Company)factory.getBean("company");
c.display();
}
}
Employee Data -> [Sahil, 101, Game development], Address -> [2, 110111, Bihar,
India]
---------
******************************************************************************
Spring – Constructor Injection with Non-String Map
---------- // Java Program to Illustrate Company Class
package com.geeksforgeeks.org;
import com.geeksforgeeks.org.Address;
import com.geeksforgeeks.org.Employee;
import java.util.*;
import java.util.Map.Entry;
public class Company {
private Map<Employee, Address> employees;
public Company(Map<Employee, Address> employees)
{
// This keyword refers to current instance itself
this.employees = employees;
}
public void display()
{
// Iterating over Map using for each loop
for (Map.Entry<Employee, Address> entry :
employees.entrySet()) {
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;
public Employee(String name, String employeeID, String department)
{
// This keyword refers to current instance itself
this.name = name;
this.employeeID = employeeID;
this.department = department;
}
public String toString()
{
return ("[" + name + "," + employeeID + ","
+ department + "]");
}
}
------------ // Java Program to Illustrate Address Class
package com.geeksforgeeks.org;
public 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;
}

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">
<bean id="employee1" class="com.geeksforgeeks.org.Employee">
<constructor-arg value="Ram"></constructor-arg>
<constructor-arg value="101"></constructor-arg>
<constructor-arg value="Software development"></constructor-arg>
</bean>
<bean id="user1" class="com.geeksforgeeks.org.Address">
<constructor-arg value="110/4"></constructor-arg>
<constructor-arg value="128933"></constructor-arg>
<constructor-arg value="Delhi"></constructor-arg>
<constructor-arg value="India"></constructor-arg>
</bean>
<bean id="company" class="com.geeksforgeeks.org.Company">
<constructor-arg>
<map>
<entry key-ref="employee1" value-ref="address1"></entry>
</map>
</constructor-arg>
</bean>
</beans>
--------- // Java Program to Illustrate Application Class
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;
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 – Constructor Injection with Map
----------------- // Java Program to illustrate Company Class
package com.geeksforgeeks.org;

public class Company {


private Map<String, String> employees;
public Company(Map<String, String> employees)
{
this.employees = employees;
}
public void display()
{
for (Map.Entry<String, String> entry :
employees.entrySet()) {

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;

public void setName(String name) { this.name = name; }


public void setemployeeID(String employeeID){ this.employeeID =
employeeID; }
public void setdepartment(String department) { this.department =
department; }
public void setAddress(Address address) { this.address = address;
}
public String getName() { return name; }
public String getemployeeID() { return employeeID; }
public String getdepartment() { return department; }
public Address getAddress() { return address; }

public void display()


{
System.out.println("Name: " + getName());
System.out.println("Employee ID: " + getEmployeeID());
System.out.println("Department: " + getDepartment());
System.out.println("Address: " + getAddress().toString());
}
}
--------
package com.geeksforgeeks.org;

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;
}

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">

<bean id="address" class="com.geeksforgeeks.org.Address">


<property name="houseNo" value="110/4"></property>
<property name="pincode" value="121212"></property>
<property name="state" value="Delhi"></property>
<property name="country" value="India"></property>
</bean>

<bean id="employee" class="com.geeksforgeeks.org.Employee">


<property name="name" value="Ram"></property>
<property name="employeeID" value="1001"></property>
<property name="department" value="Software development"></property>
<property name="address" ref="address"></property>
</bean>
</beans>
------------ // Java Program to Illustrate Application Class
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;
class Test {
public static void main(String[] args)
{
Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Employee e = (Employee)factory.getBean("employee");
e.display();
}
}
---------------
***********************
Spring – Constructor Injection with Dependent Object
--------------
package com.geeksforgeeks.org;
import com.geeksforgeeks.org.IGeek;

public class GFG {

// The object of the interface IGeek


IGeek geek;

// Constructor to set the CDI


GFG(IGeek geek) { this.geek = geek; }
}
-----
<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-2.5.xsd">
<bean id="GFG" class="com.geeksforgeeks.org.GFG">
<constructor-arg>
<bean class="com.geeksforgeeks.org.impl.CsvGFG" />
</constructor-arg>
</bean>
<bean id="CsvGFG" class="com.geeksforgeeks.org.impl.CsvGFG" />
<bean id="JsonGFG" class="com.geeksforgeeks.org.impl.JsonGFG" />
</beans>
-----
// Java Program to Illustrate Employee Class

package com.geeksforgeeks.org;
import com.geeksforgeeks.org.Address;

// Class
public class Employee {
private String name;
private String employeeID;
private String department;

// Here 'address' is an dependent object.


private Address address;

// 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;

public class Address {


private String houseNo;
private String pincode;
private String state;
private String country;

// Constructor of Address Class


public Address(String houseNo, String pincode,
String state, String country)
{
// Super keyword refers to parent class
super();
// This keyword refers to current instance itself
this.houseNo = houseNo;
this.pincode = pincode;
this.state = state;
this.country = country;
}

// 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">

<bean id="address1" class="com.geeksforgeeks.org.Address">


<constructor-arg value="110/4"></constructor-arg>
<constructor-arg value="123092"></constructor-arg>
<constructor-arg value="Delhi"></constructor-arg>
<constructor-arg value="India"></constructor-arg>
</bean>

<bean id="employee" class="com.geeksforgeeks.org.Employee">


<constructor-arg value="Ram"></constructor-arg>
<constructor-arg value="101"></constructor-arg>
<constructor-arg value="Software testing"></constructor-arg>
<constructor-arg>
<ref bean="address1"/>
</constructor-arg>
</bean>

</beans>
-----
// Java Program to Illustrate Application Class
package com.geeksforgeeks.org;

// Importing required classes from respective packages


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;

// Main(Application) class
public class Test {

// Main driver method


public static void main(String[] args)
{
// Creating new class path resource
Resource resource = new ClassPathResource(
"applicationContext.xml");

// Creating an object of BeanFactory class


BeanFactory factory = new XmlBeanFactory(resource);

// Creating an object of Employee class


Employee e = (Employee)factory.getBean("employee");
e.display();
}
}
***********************
Spring – Setter Injection with Collection
=====================================// Java program to Illustrate Company Class

package com.geeksforgeeks.org;
import java.util.*;
class Company {
private String companyName;
private List<String> employees;

public void setCompanyName(String companyName) {


this.companyName = companyName;
}

public void setEmployees(List<String> employees){


this.employees = employees;
}

public String getCompanyName() { return companyName; }

public List<String> getEmployees() { return employees; }

public void display()


{
System.out.println("Company: " + companyName);
System.out.println("Employee list: " + companyName);

for (String employee : employees) {


System.out.println("-" + employee);
}
}
}
----------
<?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">


<property name="companyName" value="GeeksForGeeks"></property>
<property name="employees">
<list>
<value>"John"</value>
<value>"Max"</value>
<value>"Sam"</value>
</list>
</property>
</bean>
</beans>
-------
// Java Program to Illustrate Application Class

package com.geeksforgeeks.org;

// Importing required classes


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;

// Application (Main) Class


public class Main {

// Main driver method


public static void main(String[] args)
{
// Creating a new class path resource
Resource resource = new ClassPathResource(
"applicationContext.xml");

// Creating an object of BeanFactory class


BeanFactory factory = new XmlBeanFactory(resource);

// Creating an object of Employee class


Employee e = (Employee)factory.getBean("employee");

// Calling display() method inside main() method


e.display();
}
}
*********************
Spring – Setter Injection with Non-String Collection
--------// Java Program to Illustrate Company Class
package com.geeksforgeeks.org;
import java.util.*;
class Company {
private String companyName;
private List<Employee> employees;

public void setCompanyName(String companyName){


this.companyName = companyName;
}

public void setEmployees(List<Employee> employees) {


this.employees = employees;
}

public String getCompanyName() { return companyName; }

public List<Employee> getEmployees(){


return employees;
}

public void display() {


System.out.println("Company: " + companyName);
System.out.println("Empoyees:");

for (Employee employee : employees) {


System.out.println(employee.toString());
}
}
}
----
// Java Program to Illustrate Employee Class

package com.geeksforgeeks.org;

// Class
class Employee {

// Class data members


private String name;
private String employeeID;
private String department;

// 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">

<bean id="employee1" class="com.geeksforgeeks.org.Employee">


<property name="name" value="John"></property>
<property name="employeeID" value="211"></property>
<property name="department" value="Penetration testing"></property>
</bean>

<bean id="employee2" class="com.geeksforgeeks.org.Employee">


<property name="name" value="Max"></property>
<property name="employeeID" value="212"></property>
<property name="department" value="Ethical hacking"></property>
</bean>

<bean id="company" class="com.geeksforgeeks.org.Company">


<property name="companyName" value="GeeksForGeeks"></property>
<property name="employees">
<list>
<ref bean="employee1"/>
<ref bean="employee2"/>
</list>
</property>
</bean>
</beans>
---------- // Java Program to Illustrate Application Class

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;
}

public String getName() { return name; }


public void setName(String name) { this.name = name; }
public String getemployeeID() { return employeeID; }
public void setemployeeID(String employeeID){
this.employeeID = employeeID;
}
public String getdepartment() { return department; }
public void setdepartment(String department) {
this.department = department;
}

public List<String> getAddress() { return address; }

public void display() {


System.out.println("Name: " + getName());
System.out.println("Employee ID: " + getEmployeeID());
System.out.println("Department: " + getDepartment());
System.out.println("Address: " + getAddress());
}
}
-----------
2) 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"
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="employee" class="com.geeksforgeeks.org.Employee">


<constructor-arg value="Ram"></constructor-arg>
<constructor-arg value="101"></constructor-arg>
<constructor-arg value="Software testing"></constructor-arg>
<constructor-arg>
<list>
<value>Gurugram</value>
<value>Haryana</value>
<value>India</value>
</list>
</constructor-arg>
</bean>

</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;

public class Test {


public static void main(String[] args) {
Resource resource = new ClassPathResource( "applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Employee e = (Employee)factory.getBean("employee");
e.display();
}
}
**********
Spring – Injecting Objects by Setter Injection
==============================
// Java Program to Illustrate Student File

// 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">

<bean id="student" class="Student">


<property name="id" value="101"/>
<property name="mathCheat">
<bean class="MathCheat"></bean>
</property>
</bean>

</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">

<bean id="studentAmiya" class="Student">


<property name="id" value="101"/>
<property name="studentName" value="Amiya Rout"/>
</bean>

<bean id="studentAsish" class="Student">


<property name="id" value="102"/>
<property 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) {
// Using ApplicationContext tom implement Spring IoC
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");

// Get the bean studentAmiya


Student amiya = context.getBean("studentAmiya", Student.class);

// Calling the methods


amiya.displayInfo();

// Get the bean studentAsish


Student asish = context.getBean("studentAsish", Student.class);

// Calling the methods


asish.displayInfo();
}
}
*********************
Spring – Injecting Literal Values By Constructor Injection
===================================================
// Java Program to Illustrate Student Class

// Class
public class Student {

// Class data members


private int id;
private String studentName;

// Getters and setters


public void setId(int id) { this.id = id; }
public void setStudentName(String studentName)
{
// This keyword refers to current instance itself
this.studentName = studentName;
}

// 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");
}

// This method executes when the spring container is closed


public void destroy() throws Exception
{
System.out.println(
"Container has been closed "+ "and I'm the destroy() method");
}
}
----------
<!DOCTYPE
beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="hw" class="beans.HelloWorld"
init-method="init" destroy-method="destroy"/>
</beans>
---------
// Java program to call the bean initialized above

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 id="studentAmiya" class="Student">

</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;

// Importing required classes


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@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;

// 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 = "prototype" / >
</ beans>
-------
<!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 = "prototype" / >
</ 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;
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);
}
}
******************************
How to Configure Dispatcher Servlet in web.xml File
======================
DispatcherServlet handles an incoming HttpRequest, delegates the request, and
processes that request
according to the configured HandlerAdapter interfaces that have been implemented
within the Spring application
along with accompanying annotations specifying handlers, controller endpoints, and
response objects.
----------
Step 1: Configure Dispatcher Servlet in web.xml File
--Go to the src > main > webapp > WEB-INF > web.xml file
-----------
<servlet>
<!-- Provide a Servlet Name -->
<servlet-name>frontcontroller-dispatcher</servlet-name>
<!-- Provide a fully qualified path to the DispatcherServlet class -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
</servlet>
****************
Spring – When to Use Factory Design Pattern Instead of Dependency Injection
====================
Dependency Injection, it is used for loosely coupled software components, It is not
aware of any container
factory for creating of bean and is only aware of the dependency this makes the
class easier for testing
-----
public class FactoryProduct{
// Instance of OperatingSystem
private OperatingSystem OS;
public void setAddress(Address address){
this.address=address;
}
}
----
In Factory Design, it creates various instances of a class without necessarily
knowing what kind of object
it creates or how to create it.
The client is responsible for managing the factory class and
to call the getInstance() method to create an instance of the class.
This also makes the unit testing difficult as you would need a factory object in
order to unit test.
-----
// Dependent class
public class FactoryProduct{
public static void Main(String[] str){
// Instance of OperatingSystemFactory class
OperatingSystemFactory osfactory = new OperatingSystemFactory();
// Getting the instance
OperatingSystem obj = osfactory.getInstance("windows");
obj.cpu();
}
}
----------
When to use Factory Design
------
A class does not know the type of object before its creation.
A class requires its subclasses to specify the objects it creates.
You want to localize the logic of your program to instantiate an instance of the
class.
It is useful when you need to abstract the creation of an object away from its
actual implementation.
*******************
How to Create a Simple Spring Application?
=========================
@RestController
public class Controller {
@GetMapping("/hello/{name}/{age}") //localhost:8080/hello/Aayush/2
public void insert(@PathVariable("name") String name, @PathVariable("age") int
age) {
System.out.println(name);
System.out.println(age);
}
}
*****************
Spring – init() and destroy() Methods with Example
===============
init-method is the attribute of the spring <bean> tag.
It is utilized to declare a custom method for the bean that will act as the bean
initialization method
<bean id="student" class="com.amiya.Student" init-method="myPostConstruct">
-----
destroy() method will be called before the bean is removed from the container
destroy-method is bean attribute using which we can assign a custom bean method
that will be called just before the bean is destroye.
<bean id="student" class="com.amiya.Student" destroy-method="myPreDestroy">
--------
**********
We are going to explain init() and destroy() Methods through
@PostConstruct and @PreDestroy Annotation by simply creating a Spring JDBC project.
So let’s create a Spring JDBC project first.
*************************************
Spring – Project Modules
================
****************
What is Ambiguous Mapping in Spring?
===============
1. Using ‘name = ‘ instead of ‘value = ‘
--------@RequestMapping(name = "/getName", method = GET)
--------// Changed 'name' to 'value'
@RequestMapping(value = "/getName", method = GET)
2. No parent mapping on the Rest Controller
--------
package com.geeksforgeeks.ambiguousmapping.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@RequestMapping(value = "/writeArticles")
public String writeArticles() {
return "5 Articles written on GeeksForGeeks !";
}
@RequestMapping(value = "/doLaundry")
public String doLaundry() {
return "Laundry done at 5 PM !";
}
}
------
*************
Spring Framework Standalone Collections
=============
************
https://www.geeksforgeeks.org/how-to-transfer-data-in-spring-using-dto/?ref=lbp
==============
********************
Spring Application Without Any .xml Configuration
=============
https://www.geeksforgeeks.org/spring-application-without-any-xml-configuration/?
ref=lbp
****************
Spring – REST Pagination (https://www.geeksforgeeks.org/spring-rest-pagination/?
ref=lbp)
==============
***********
Spring Framework Annotations
=====================
Type 1: Spring Core Annotations
------------
@Autowired
@Qualifier
@Primary
@Bean
@Lazy
@Required
@Value
@Scope
@Lookup, etc.
Context Configuration Annotations
@Profile
@Import
@ImportResource
@PropertySource, etc.
+++++++
Type 2: Spring Web Annotations
------------
@RequestMapping
@RequestBody
@PathVariable
@RequestParam
Response Handling Annotations
@ResponseBody
@ExceptionHandler
@ResponseStatus
@Controller
@RestController
@ModelAttribute
@CrossOrigin
+++++++++++++++++
@SpringBootApplication ------- It encapsulates @Configuration,
@EnableAutoConfiguration, and @ComponentScan annotations
++++++++++++
Type 4: Spring Scheduling Annotations
-------------
@EnableAsync
@EnableScheduling
@Async
@Scheduled
@Schedules
++++++++++
Type 5: Spring Data Annotations
-----------
@Transactional
@NoRepositoryBean
@Param
@Id
@Transient
@CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate
Spring Data JPA Annotations
@Query
@Procedure
@Lock
@Modifying
@EnableJpaRepositories
Spring Data Mongo Annotations
@Document
@Field
@Query
@EnableMongoRepositories
++++++++++
Type 6: Spring Bean Annotations
-----------
@ComponentScan
@Configuration
++++++++++++++
Stereotype Annotations
---------------
@Component
@Service
@Repository
@Controller
******************
Spring MVC
==========https://www.geeksforgeeks.org/spring-mvc/?ref=lbp
index
------------
Spring MVC – Basics
Software Setup and Configuration (STS/Eclipse/IntelliJ)
Prerequisite (Spring Core Concepts)
Core Spring MVC
Spring MVC – Annotation
Spring MVC – Form Handling
Spring MVC with JSTL
Spring MVC with REST API
Spring MVC with Database
*************
Spring MVC – Basics
----------
Spring MVC Framework follows the Model-View-Controller architectural design pattern
It works around the Front Controller i.e. the Dispatcher Servlet.
Dispatcher Servlet handles and dispatches all the incoming HTTP requests to the
appropriate controller.
It uses @Controller and @RequestMapping as default request handlers.
@RequestMapping annotation maps web requests to Spring Controller methods.
---
Model: The Model encapsulates the application data/with business logic.
View: View renders the model data and generates HTML output that the client’s
browser can interpret.
Controller: The Controller processes the user requests and passes them to the view
for rendering.
------
Spring MVC Framework works
----
All the incoming requests are intercepted by the DispatcherServlet that works as
the front controller.
The DispatcherServlet then gets an entry of handler mapping from the XML file and
forwards the request to the controller.
The object of ModelAndView is returned by the controller.
The DispatcherServlet checks the entry of the view resolver in the XML file and
invokes the appropriate view component.
------
Create Your First Spring MVC Application
------------
Step 0: Setup your project with maven use the required archtype to get the required
folders directory and configure the server with your project.
Step 1: Load the spring jar files or add the dependencies if Maven is used. Add the
following dependencies in pom.xml
----
@Controller
public class HelloGeek {
@RequestMapping("/")
public String display()
{
return "hello";
}
}
----web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
------spring-servlet.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- This element defines the base-package where


DispatcherServlet will search the controller class. -->
<context:component-scan base-package="com.geek" />

<!--Provide support for conversion,


formatting and also for validation -->
<mvc:annotation-driven/>
</beans>
---------index.jsp
<html>
<body>
<p>Spring MVC Tutorial!!</p>
</body>
</html>
**************************
Spring MVC using Java based configuration
-------------
https://www.geeksforgeeks.org/spring-mvc-using-java-based-configuration/?ref=lbp
*****************
ViewResolver in Spring MVC
========
How to Create Your First Model in Spring MVC?
=========
Spring MVC CRUD with Example

You might also like