Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

 Spring Introduction?  What is Spring?

It is an application framework that is used to create Enterprise applications in Java using IoC Container, Dependency Injection, Spel, AOP, and other important features.


Spring Framework specially design to provide better flexibility and performance to Java Enterprise Application.


Java provides better security but less flexibility to a distributed design pattern that's why Spring Framework and Struts Framework have been launched.


It has been created to enhance EJB(Enterprise Java Bean) because EJB is complex for configuration and it requires higher resources.

\


What is Spring History?

The first version of the Spring framework was written by Rod Johnson in 2002. 

The framework was first released in June 2003 under the Apache license version 2.0. 

The first milestone release of the Spring framework (1.0) was released in March 2004. 

Spring 2.0, which came in 2006, simplified the XML config files.

Spring 2.5, which came in 2007, introduced annotation configurations.

Spring 3.2, which came in 2012, introduced Java configuration, had support for Java 7, Hibernate 4, Servlet 3.0, and also required a minimum of Java 1.5. 

Spring 4.0, which came in 2014, had support for Java 8. 

Spring Boot also was introduced in 2014.

Spring 5.0 came out in 2017. Spring Boot 2.x has support for Spring 5.



What are Core Spring, Spring MVC, and Spring Boot?

Spring Core is used to create normal enterprise applications using a distributed system. but it can not be managed by Web applications.


Spring MVC is the enhancement of Spring Core and it can be used in Java Web Application Development.

It uses JSP, JSF, Servlet, Bean, Hibernate, and JDBC


Spring boot is the REST application framework that provides API (Application Programming Interface) that can be used in Web & Mobile Applications.

It is also used to implement java Microservice features under Web application. It is a completely based annotation.



Create First Application of Spring Core:-

1) First Create Normal Java Project using Eclipse, IntelliJ, or Netbeans

2)  Add Jar File under Project

3)  Create a package and create beans class(it is a normal java class that contain properties)

4)  create applicationContext.xml file and Inject class property

5)  Create a Main class to call application context and inject application object



Code of Bean Class:-

package com.scs;

public class Student {
private int rno;
private String sname;

public int getRno() {
return rno;
}

public void setRno(int rno) {
this.rno = rno;
}

public String getSname() {
return sname;
}

public void setSname(String sname) {
this.sname = sname;
}
}


Code of applicationContext.xml (inside of src folder)

    <?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="stu" class="com.scs.Student">
<property name="rno" value="1001" ></property>
<property name="sname" value="xyz" ></property>
</bean>
</beans>

Code of Main Class:-

package com.scs;

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 Main {

public static void main(String[] args) {
Resource res = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(res);
Student s = (Student) factory.getBean("stu");
s.setRno(1002);
s.setSname("Manish Kumar");
System.out.println(s.getRno() + "" +s.getSname());
}
}

 


Download Download Source Code



Create a Simple Interest Program using UAO, BAO, and DAO with Setter Injection?

Create Class for SI:-


package com.scs.dao;

public class SI {
private float p;
private float r;
private float t;

public float getP() {
return p;
}

public void setP(float p) {
this.p = p;
}

public float getR() {
return r;
}

public void setR(float r) {
this.r = r;
}

public float getT() {
return t;
}

public void setT(float t) {
this.t = t;
}
}


Create Class for Business Code:-

package com.scs.bao;

public class SILogic {
public float CalculateSI(float p,float r,float t)
{
return (p*r*t)/100;
}
}
Create SIMain Class:-

package com.scs.uao;

import com.scs.bao.SILogic;
import com.scs.dao.SI;
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 SIAccess {
public static void main(String[] args) {
// Resource res = new ClassPathResource("applicationContext.xml");
// BeanFactory bf = new XmlBeanFactory(res);
ApplicationContext bf = new ClassPathXmlApplicationContext("applicationContext.xml");
SI s = (SI)bf.getBean("si");
float output = new SILogic().CalculateSI(s.getP(),s.getR(),s.getT());
System.out.println(output);
}
}
    
SIAccess.Java:-

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="si" class="com.scs.dao.SI">
<property name="p" value="50000" ></property>
<property name="r" value="2" ></property>
<property name="t" value="2" ></property>
</bean>
</beans>
How many Ways to implement dependency Injection:-

We can implement dependency Injection using two different ways:-

1)  By Setter Method:-

In the above example, we have created property means getter and setter that is the approach to implement setter injection.


2)  By Constructor:-

Using this we can inject the functionality of the object using constructor block, we will define <constructor-arg> tag to inject constructor under XML file.


Difference between constructor and setter injection

  1. Difference between constructor and setter injection

There are many key differences between constructor injection and setter injection.

  1. Partial dependency: can be injected using setter injection but it is not possible by constructor. Suppose there are 3 properties in a class, having 3 arg constructor and setters methods. In such case, if you want to pass information for only one property, it is possible by the setter method only.
  2. Overriding: Setter injection overrides the constructor injection. If we use both constructor and setter injection, the IOC container will use the setter injection.
  3. Changes: We can easily change the value by setter injection. It doesn't create a new bean instance always like a constructor. So setter injection is flexible than constructor injection.
Step for Constructor Injection:-

1)  Create bean class and define constructor block


package concept;

public class Student {
private String name;
Student()
{
this.name="xyz";
}
Student(String name)
{
this.name=name;
}

public void show(){
System.out.print(this.name);
}

}

2)  Create applicationContext.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"
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="studentbean" class="concept.Student">  
<constructor-arg value="Pawan Rawat" type="String"></constructor-arg>  
</bean>  
  
</beans>  


3)  Create Main Class File to Call this

package client;

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;

import concept.Student;

public class TestClass {

public static void main(String[] args) {
Resource res = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(res);
Student s =(Student) factory.getBean("studentbean");
     s.show();
}

}


Example of Constructor Injection using Map:-

Step1st:-
Create bean class under package:-

package concept;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Student {
private String name;

Map mp;

Student(String name,Map mp)
{
this.name=name;
this.mp=mp;
}

public void showMapData()
{
System.out.println("Name is "+name);
System.out.println("Data of Map is");
Set<Map.Entry<String,String>> se = mp.entrySet();
for(Map.Entry<String,String> s : se)
{
System.out.println(s.getKey() + " "+s.getValue());
}
}

}

Step2nd:-

Create a configuration file  and define String  and Map Type Arguments


<?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="studentbean" class="concept.Student">  
<constructor-arg value="Pawan Rawat" type="String"></constructor-arg>
<constructor-arg>
<map>
<entry key="advance" value="java"></entry>
<entry key="medium" value="python"></entry>
<entry key="primary" value="c/c++"></entry> 
</map>

</constructor-arg>  
</bean>  
  
</beans>  


Step3rd:-

Create Client Code Class 

package client;

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;

import concept.Student;

public class TestClass {

public static void main(String[] args) {
Resource res = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(res);
Student s =(Student) factory.getBean("studentbean");
       s.showMapData();
}

}



Create Simple Interest Program using Constructor Injection?

Step1st:-
Create bean class and define three parameterized constructors
package concept;

public class SI {
private float p,r,t;
public SI(float p, float r, float t)
{
this.p=p;
this.r=r;
this.t=t;
}
public void calcSi()
{
System.out.println("Result is "+(p*r*t)/100);
}

}


Step2nd:-

Create config 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"
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="sibean" class="concept.SI">  
<constructor-arg value="45000" type="float"></constructor-arg>
<constructor-arg value="4.5" type="float"></constructor-arg>
<constructor-arg value="2" type="float"></constructor-arg>
</bean>  
  
</beans>  


Step3rd:-

Write Client Code 

package client;

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;

import concept.SI;
import concept.Student;

public class TestSI {

public static void main(String[] args) {
Resource res = new ClassPathResource("siContext.xml");
BeanFactory factory = new XmlBeanFactory(res);
SI s =(SI) factory.getBean("sibean");
    s.calcSi();
  

}

}



What is Autowiring in Spring Core?

It is another feature of the Spring framework, using this we can implicitly inject the property of the object.

Autowiring is used to provide dependency injection using the object.

We can not inject primitive type and String type data using autowiring, it can only inject objects.

Metadata for Autowiring:-

Autowiring modes

There are many autowiring modes:


No.

Mode

Description

1)

no

It is the default autowiring mode. It means no autowiring bydefault.

2)

byName

The byName mode injects the object dependency according to the name of the bean. In such a case, property name and bean name must be the same. It internally calls setter method.

3)

byType

The byType mode injects the object dependency according to type. So property name and bean name can be different. It internally calls setter method.

4)

constructor

The constructor mode injects the dependency by calling the constructor of the class. It calls the constructor having a large number of parameters.

5)

autodetect

It is deprecated since Spring 3.



Example of Autowiring?

1)  Create package and name it's aw

package aw;

public class A {
B b;  
A(){
System.out.println("a is created");
}  
public B getB() 
{  
    return b;  
}  
public void setB(B b) 
{  
    this.b = b;  
}  
void print(){
System.out.println("hello a");
}  
void display(){  
    print();  
    b.print();  
}  

}


2)  B.java

package aw;

public class B {
B()
{
System.out.println("b is created");
}  
void print()
{
System.out.println("hello b");
}  
  

}


3)      Test.java


package aw;

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

public class Test {

public static void main(String[] args) {
  ApplicationContext context=new ClassPathXmlApplicationContext("autoWireContext.xml");  
  A a=context.getBean("a",A.class);  
  a.display();  


}

}


4) Create autoWireContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="b" class="com.aw.B"></bean>
<bean id="a" class="com.aw.A" autowire="byName"></bean>


</beans>

2) byType autowiring mode

In the case of byType autowiring mode, bean id and reference name may be different. But there must be only one bean of a type.

It internally uses setter injection.

1.       <bean id="b1" class="scs.B"></bean>  

2.       <bean id="a" class="scs.A" autowire="byType"></bean>  

In this case, it works fine because you have created an instance of B type. It doesn't matter that you have different bean name than reference name.

But, if you have multiple beans of one type, it will not work and throw exception.

Let's see the code where are many bean of type B.

1.       <bean id="b1" class="scs.B"></bean>  

2.       <bean id="b2" class="scs.sssit.B"></bean>  

3.       <bean id="a" class="scs.A" autowire="byName"></bean>  

In such case, it will throw exception.


3) constructor autowiring mode

In the case of constructor autowiring mode, spring container injects the dependency by a highest parameterized constructor.

If you have 3 constructors in a class, zero-arg, one-arg and two-arg then injection will be performed by calling the two-arg constructor.

1.       <bean id="b" class="scs.B"></bean>  

2.       <bean id="a" class="scs.A" autowire="constructor"></bean>  


4) no autowiring mode

In case of no auto wiring mode, the spring container doesn't inject the dependency by autowiring.

1.       <bean id="b" class="scs.B"></bean>  

2.       <bean id="a" class="scs.A" autowire="no"></bean>  





Dependency Injection with Factory Method in Spring

Spring framework provides a facility to inject beans using the factory method. To do so, we can use two attributes of the bean element.

  1. factory-method represents the factory method that will be invoked to inject the bean.
  2. factory-bean: represents the reference of the bean by which factory method will be invoked. It is used when the factory method is non-static.

A method that returns an instance of a class is called factory method.

1.       public class A {  

2.       public static A getA(){//factory method  

3.           return new A();  

4.       }  

5.       }  



Factory Method Types

There can be three types of factory methods:

1) A static factory method that returns instances of its own class. It is used in singleton design patterns.

1.       <bean id="a" class="com.scs.A" factory-method="getA"></bean>  

2) A static factory method that returns instance of another class. It is used instance is not known and decided at runtime.

1.       <bean id="b" class="com.scs.A" factory-method="getB"></bean>  

3) A non-static factory method that returns instance of another class. It is used instance is not known and decided at runtime.

1.       <bean id="a" class="com.scs.A"></bean>  

2.       <bean id="b" class="com.scs.A" factory-method="getB" factory-bean="a"></bean>  



Implement Factory Method:-
package com.factoryexample;

public class A {
private static final A obj=new A();
private A()
{
System.out.println("private constructor");
}
public static A getA()
{
System.out.println("factory method ");
return obj;
}

public void msg()
{
System.out.println("hello user");
}


}

SpringFactoryContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="a" class="com.factoryexample.A" factory-method="getA"></bean>
</beans>


Test.java

package com.factoryexample;

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

public class Test {

public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("springFactoryContext.xml");
A a=(A)context.getBean("a");
a.msg();

}
}

Implement Factory Method with FactoryBean:-

It is used to call the nonstatic method under bean class.
package com.factoryexample;

public class A {
private static final A obj=new A();
private A()
{
System.out.println("private constructor");
}
public A getA()
{
System.out.println("factory method ");
return obj;
}

public void msg()
{
System.out.println("hello user");
}


}
package com.factoryexample;

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

public class Test {

public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("springFactoryContext.xml");
A a=(A)context.getBean("a");
a.msg();

}
}

What is AOP?

AOP means aspect-oriented programming, it is a complement of OOP (Object-oriented programming).

It provides modularity into the application that can be called and modified dynamically.

AOP method is called "concern" that can be added and modified dynamically with a flexible approach.



Where do we use AOP?

1)  if we require to modify, acknowledge and provide notification to any class repeatedly.

2)  It allows users to implement custom aspects(class)



AOP Terminology:-

1)  Join point:-  It is called accessibility of method, fields, and exception, in spring core we only use method accessbility.

2)  Advice:-  which action will be implemented under Joinpoint is managed by Advice. there are different types of advice.

o    Before Advice: it executes before a join point.

o    After Returning Advice: it executes after a join point completes normally.

o    After Throwing Advice: it executes if the method exits by throwing an exception.

o    After (finally) Advice: it executes after a join point regardless of join point exit whether normally or exceptional return.

o    Around Advice: It executes before and after a join point.


    Point Cut:-

    It is an expression language to implement join points match operation

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,......................................................

Introduction

It means the introduction of additional methods and fields for a type. It allows you to introduce a new interface to any advised object.



Target Object

It is the object i.e. being advised by one or more aspects. It is also known as a proxied object in spring because Spring AOP is implemented using runtime proxies.

Aspect

It is a class that contains advice, joinpoints, etc.

Interceptor

It is an aspect that contains only one advice.


AOP Proxy

It is used to implement aspect contracts, created by the AOP framework. It will be a JDK dynamic proxy or CGLIB proxy in the spring framework.


Weaving

It is the process of linking aspects with other application types or objects to create an advised object. Weaving can be done at compile-time, load time or runtime. Spring AOP performs weaving at runtime



Where AOP will be implemented?


1)  AspectJ

2) SPRING AOP

3)  JBOSS AOP



Example of Before Advice:-


1)  Create Class A:-

package aop;


public class A {

public void fun()

{

System.out.println("This is Interceptor Aspect");

}

}


2) 

2)  package aop;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class BeforeMethodExample implements MethodBeforeAdvice {

    @Override
public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
    System.out.println("additional concern before actual logic");  
}  


333)
papackage aop;

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 r=new ClassPathResource("aopApplicationContext.xml");  
BeanFactory factory=new XmlBeanFactory(r);  
A a=factory.getBean("proxy",A.class);  
a.fun();  


}

}




}
























Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post