0% found this document useful (0 votes)
4 views

Java Unit V

Uploaded by

Mohammad kaif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Unit V

Uploaded by

Mohammad kaif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Object Oriented Programming with Java [Document title]

UNIT-5

Spring Framework

It was developed by Rod Johnson in 2003. Spring framework makes the easy
development of JavaEE application.

Spring is a lightweight framework. It can be thought of as a framework of


frameworks because it provides support to various frameworks such as Struts, Hibernate,
Tapestry, EJB, JSF, etc. The framework, in broader sense, can be defined as a structure
where we find solution of the various technical problems.

The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM,
WEB MVC etc. We will learn these modules in next page. Let's understand the IOC and
Dependency Injection first.

Inversion Of Control (IOC) and Dependency Injection

These are the design patterns that are used to remove dependency from the
programming code. They make the code easier to test and maintain. Let's understand this
with the following code:

class Employee{
Address address;
Employee()
{
address=new Address();
}}

In such case, there is dependency between the Employee and Address (tight coupling). In
the Inversion of Control scenario, we do this something like this:

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

class Employee{
Address address;
Employee(Address address)
{
this.address=address;
}}

Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the
code if our logic is moved to new environment.

In Spring framework, IOC container is responsible to inject the dependency. We provide


metadata to the IOC container either by XML file or annotation.

Advantage of Dependency Injection

o makes the code loosely coupled so easy to maintain


o makes the code easy to test

Example-2

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Advantages of Spring Framework


There are many advantages of Spring Framework. They are as follows:

1) Predefined Templates
o Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies.
So there is no need to write too much code. It hides the basic steps of these technologies.
o Let's take the example of JdbcTemplate, you don't need to write the code for
exception handling, creating connection, creating statement, committing transaction,
closing connection etc. You need to write the code of executing query only. Thus, it save
a lot of JDBC code.

2) Loose Coupling

o The Spring applications are loosely coupled because of dependency injection.

3) Easy to test

o The Dependency Injection makes easier to test the application. The EJB or Struts
application require server to run the application but Spring framework doesn't require
server.

4) Lightweight

o Spring framework is lightweight because of its POJO implementation. The Spring


Framework doesn't force the programmer to inherit any class or implement any interface.
That is why it is said non-invasive.

5) Fast Development

o The Dependency Injection feature of Spring Framework and it support to various


frameworks makes the easy development of JavaEE application.

6) Powerful abstraction

o It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA


and JTA.

7) Declarative support
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

o It provides declarative support for caching, validation, transactions and formatting.

Spring Modules (Spring Framework Architecture)


The Spring framework comprises of many modules such as core, beans, context,
expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS,
Transaction, Web, Servlet, Struts etc. These modules are grouped into Test, Core
Container, AOP, Aspects, Instrumentation, Data Access / Integration, Web (MVC /
Remoting) as displayed in the following diagram.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Test
This layer provides support of testing with JUnit and TestNG.
Spring Core Container

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

The Spring Core container contains core, beans, context and expression language (EL)
modules.
Core and Beans
These modules provide IOC and Dependency Injection features.
Context
This module supports internationalization (I18N), EJB, JMS, Basic Remoting.

Expression Language
It is an extension to the EL defined in JSP. It provides support to setting and getting
property values, method invocation, accessing collections and indexers, named variables,
logical and arithmetic operators, retrieval of objects by name etc.
AOP, Aspects and Instrumentation
These modules support aspect oriented programming implementation where you can use
Advices, Pointcuts etc. to decouple the code.
The aspects module provides support to integration with AspectJ.
The instrumentation module provides support to class instrumentation and classloader
implementations.
Data Access / Integration
This group comprises of JDBC, ORM, OXM, JMS and Transaction modules. These modules
basically provide support to interact with the database.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

How to work Spring

First Spring Program


Steps to create spring application
1) Create Java class
This is the simple java bean class containing the name property only.

package myspring;
public class Student
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

public void displayInfo()

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

{
System.out.println("Hello: "+name);
}
}

This is simple bean class, containing only one property name with its getters and setters
method. This class contains one extra method named displayInfo() that prints the
student name by the hello message.

2) Create the xml file


In case of myeclipse IDE, you don't need to create the xml file as myeclipse does this for
yourselves. Open the applicationContext.xml file, and write the following code:

<?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="myspring.Student">


<property name="name" value="Dhara Singh"></property>
</bean>

</beans>

The bean element is used to define the bean for the given class.
The property subelement of bean specifies the property of the Student class named
name. The value specified in the property element will be set in the Student class object
by the IOC container.

3) Create the test class

Create the java class e.g. Test. Here we are getting the object of Student class from the
IOC container using the getBean() method of BeanFactory. Let's see the code of test class.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

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

Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}

The Resource object represents the information of applicationContext.xml file. The


Resource is the interface and the ClassPathResource is the implementation class of the
Reource interface. The BeanFactory is responsible to return the bean.
The XmlBeanFactory is the implementation class of the BeanFactory. There are many
methods in the BeanFactory interface. One method is getBean(), which returns the object
of the associated class.

4) Load the jar files required for spring framework

There are mainly three jar files required to run this application.

o org.springframework.core-3.0.1.RELEASE-A
o com.springsource.org.apache.commons.logging-1.1.1
o org.springframework.beans-3.0.1.RELEASE-A

For the future use, You can download the required jar files for spring core application.
5) Run the test class
Now run the Test class. You will get the output Hello: Dhara Singh

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

IoC Container
The IoC container is responsible to instantiate, configure and assemble the objects. The
IoC container gets informations from the XML file and works accordingly. The main tasks
performed by IoC container are:

o to instantiate the application class


o to configure the object
o to assemble the dependencies between the objects

There are two types of IoC containers. They are:

1. BeanFactory
2. ApplicationContext

Difference between BeanFactory and the ApplicationContext

• The org.springframework.beans.factory.BeanFactory and the


org.springframework.context.ApplicationContext interfaces acts as the IoC container.
The ApplicationContext interface is built on top of the BeanFactory interface.
• It adds some extra functionality than BeanFactory such as simple integration with
Spring's AOP, message resource handling (for I18N), event propagation, application
layer specific context (e.g. WebApplicationContext) for web application. So it is better to
use ApplicationContext than BeanFactory.

Using BeanFactory

The XmlBeanFactory is the implementation class for the BeanFactory interface. To use the
BeanFactory, we need to create the instance of XmlBeanFactory class as given below:

Resource resource=new ClassPathResource("applicationContext.xml");

BeanFactory factory=new XmlBeanFactory(resource);

The constructor of XmlBeanFactory class receives the Resource object so we need to pass
the resource object to create the object of BeanFactory.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Using ApplicationContext

The ClassPathXmlApplicationContext class is the implementation class of


ApplicationContext interface. We need to instantiate the ClassPathXmlApplicationContext
class to use the ApplicationContext as given below:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"


);
The constructor of ClassPathXmlApplicationContext class receives string, so we can pass the name
of the xml file to create the instance of ApplicationContext.

Dependency Injection in Spring


Dependency Injection (DI) is a design pattern that removes the dependency from the
programming code so that it can be easy to manage and test the application. Dependency
Injection makes our programming code loosely coupled. To understand the DI better,
Let's understand the Dependency Lookup (DL) first:

Dependency Lookup
The Dependency Lookup is an approach where we get the resource after demand. There
can be various ways to get the resource for example:

A obj = new AImpl();

In such way, we get the resource(instance of A class) directly by new keyword. Another
way is factory method:

A obj = A.getA();

This way, we get the resource (instance of A class) by calling the static factory method
getA().

Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:

Context ctx = new InitialContext();

Context environmentCtx = (Context) ctx.lookup("java:comp/env");

A obj = (A)environmentCtx.lookup("A");

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

There can be various ways to get the resource to obtain the resource. Let's see the
problem in this approach.

Problems of Dependency Lookup

There are mainly two problems of dependency lookup.

o tight coupling The dependency lookup approach makes the code tightly coupled.
If resource is changed, we need to perform a lot of modification in the code.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

o Not easy for testing This approach creates a lot of problems while testing the
application especially in black box testing.

Dependency Injection
The Dependency Injection is a design pattern that removes the dependency of the
programs. In such case we provide the information from the external source such as XML
file. It makes our code loosely coupled and easier for testing. In such case we write the
code as:
class Employee{
Address address;

Employee(Address address){
this.address=address;
}
public void setAddress(Address address){
this.address=address;
}

In such case, instance of Address class is provided by external souce such as XML file
either by constructor or setter method.

Two ways to perform Dependency Injection in Spring framework

1. Dependency Injection by Constructor Example

We can inject the dependency by constructor. The <constructor-arg> subelement


of <bean> is used for constructor injection. Here we are going to inject

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Injecting primitive and string-based values

simple example to inject primitive and string-based values. We have created three files
here:
o Employee.java
o applicationContext.xml
o Test.java

Employee.java

It is a simple class containing two fields id and name. There are four constructors and one
method in this class.
package myspring;

public class Employee {


private int id;
private String name;
public Employee()
{
System.out.println("def cons");
}
public Employee(int id)
{
this.id = id;
}
public Employee(String name)
{
this.name = name;
}
public Employee(int id, String name)
{
this.id = id;
this.name = name;
}
void show(){
System.out.println(id+" "+name);
}

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

applicationContext.xml

We are providing the information into the bean by this file. The constructor-arg element
invokes the constructor. In such case, parameterized constructor of int type will be
invoked. The value attribute of constructor-arg element will assign the specified value.
The type attribute specifies that int parameter constructor will be invoked.

<?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="e" class="myspring.Employee">

<constructor-arg value="10" type="int"></constructor-arg>

</bean>

</beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the show method.
package myspring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;

public class Test {


public static void main(String[] args) {
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Resource r=new ClassPathResource("applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(r);

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

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

s.show();

}
}

Constructor Injection with Dependent Object

If there is HAS-A relationship between the classes, we create the instance of dependent
object (contained object) first then pass it as an argument of the main class constructor.
Here, our scenario is Employee HAS-A Address. The Address class object will be termed
as the dependent object. Let's see the Address class first:

Address.java

This class contains three properties, one constructor and toString() method to return the
values of these object.
package myspring;

public class Address {


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

public Address(String city, String state, String country) {


super();
this.city = city;
this.state = state;
this.country = country;
}

public String toString(){


return city+" "+state+" "+country;
}
}

Employee.java

It contains three properties id, name and address(dependent object) ,two constructors
and show() method to show the records of the current object including the depedent
object.

package myspring;

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

public class Employee {


private int id;
private String name;
private Address address;//Aggregation

public Employee() {System.out.println("def cons");}

public Employee(int id, String name, Address address) {


super();
this.id = id;
this.name = name;
this.address = address;
}

void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}

applicationContext.xml

The ref attribute is used to define the reference of another object, such way we are
passing the dependent object as an constructor argument.

<?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="a1" class="myspring.Address">

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

<constructor-arg value="ghaziabad"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg value="India"></constructor-arg>
</bean>

<bean id="e" class="myspring.Employee">


<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value="Sonoo"></constructor-arg>
<constructor-arg>
<ref bean="a1"/>
</constructor-arg>
</bean>

</beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the show method.

package myspring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;

public class Test {


public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(r);

Employee s=(Employee)factory.getBean("e");
s.show();

}
}

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Dependency Injection by setter method


We can inject the dependency by setter method also. The <property> subelement
of <bean> is used for setter injection. Here we are going to inject

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

Injecting primitive and string-based values by setter method

We have created three files here:

o Employee.java
o applicationContext.xml
o Test.java

Employee.java

It is a simple class containing three fields id, name and city with its setters and getters and
a method to display these informations.

package myspring;
public class Employee {
private int id;
private String name;
private String city;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

public String getCity() {


return city;

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

}
public void setCity(String city) {
this.city = city;
}
void display(){
System.out.println(id+" "+name+" "+city);
}

applicationContext.xml

We are providing the information into the bean by this file. The property element invokes
the setter method. The value subelement of property will assign the specified value.

<?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="obj" class="myspring.Employee">


<property name="id">
<value>20</value>
</property>
<property name="name">
<value>Arun</value>
</property>
<property name="city">
<value>ghaziabad</value>
</property>

</bean>

</beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the display method.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

package myspring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;

public class Test {


public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(r);

Employee e=(Employee)factory.getBean("obj");
s.display();

}
}

What is AOP
One of the key components of Spring Framework is the Aspect oriented programming
(AOP) framework. Aspect-Oriented Programming entails breaking down program logic into
distinct parts called so-called concerns. The functions that span multiple points of an application
are called cross-cutting concerns and these cross-cutting concerns are conceptually separate
from the application's business logic. There are various common good examples of aspects like
logging, auditing, declarative transactions, security, caching, etc.

The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the
aspect. Dependency Injection helps you decouple your application objects from each other and
AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like
triggers in programming languages such as Perl, .NET, Java, and others.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

AOP Terminologies
These terms are not specific to Spring, rather they are related to AOP.
1
Aspect

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

This is a module which has a set of APIs providing cross-cutting requirements. For
example, a logging module would be called AOP aspect for logging. An application can
have any number of aspects depending on the requirement.

Join point
This represents a point in your application where you can plug-in the AOP aspect. You
2
can also say, it is the actual place in the application where an action will be taken using
Spring AOP framework.

Advice
This is the actual action to be taken either before or after the method execution. This is an
3
actual piece of code that is invoked during the program execution by Spring AOP
framework.

Pointcut
4 This is a set of one or more join points where an advice should be executed. You can
specify pointcuts using expressions or patterns as we will see in our AOP examples.

Introduction
5
An introduction allows you to add new methods or attributes to the existing classes.

Target object
6 The object being advised by one or more aspects. This object will always be a proxied
object, also referred to as the advised object.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

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

Spring - Bean Scopes


• When defining a <bean> you have the option of declaring a scope for that bean. For
example, to force Spring to produce a new bean instance each time one is needed,
you should declare the bean's scope attribute to be prototype. Similarly, if you want
Spring to return the same bean instance each time one is needed, you should declare
the bean's scope attribute to be singleton.

The following table describes the supported scopes:


Table 1. Bean scopes
Scope Description
singleton (Default) Scopes a single bean definition to a single object instance for each
Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

request Scopes a single bean definition to the lifecycle of a single HTTP request. That is,
each HTTP request has its own instance of a bean created off the back of a single
bean definition. Only valid in the context of a web-aware
Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in
the context of a web-aware Spring ApplicationContext.
application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in
the context of a web-aware Spring ApplicationContext.
websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the
context of a web-aware Spring ApplicationContext.

The singleton scope

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

<!-- A bean definition with singleton scope -->


<bean id = "..." class = "..." scope = "singleton">
<!-- collaborators and configuration for this bean go here -->
</bean>
Example
The following steps to create a Spring application −
Steps Description
1 Create a project with a name SpringExample and create a package com.tutorialspoint under
the src folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello
World Example chapter.
3 Create Java classes HelloWorld and MainApp under the com.tutorialspoint package.
4 Create Beans configuration file Beans.xml under the src folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the
application as explained below.
Here is the content of HelloWorld.java file −

package myspring;

public class HelloWorld {


private String message;

public void setMessage(String message){


this.message = message;
}
public void getMessage(){

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

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


}
}

MainApp.java file −
package myspring;

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

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

objA.setMessage("I'm object A");


objA.getMessage();

HelloWorld objB = (HelloWorld) context.getBean("helloWorld");


objB.getMessage();
}
}

The configuration file Beans.xml required for singleton scope −

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

<beans xmlns = "http://www.springframework.org/schema/beans"


xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld" scope = "singleton">
</bean>
</beans>

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

What are WebSockets


Following are some of the drawbacks of HTTP due to which they are unsuitable for certain
scenarios-

• Traditional HTTP requests are unidirectional - In traditional client server


communication, the client always initiates the request.
• Half Duplex - User requests for a resource and the server then serves it to the client. The
response is only sent after the request. So at a time only a single request occurs.
• Multiple TCP connections - For each request a new TCPsession is needed to be
established and then closed after receiving the response. So without using WebSockets
we will have multiple sessions.
• Heavy - Normal HTTP request and response require exchange of extra data between
client and server.
WebSocket is a computer communications protocol, providing full-duplex communication
channels over a single TCP connection.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Auto wiring
• It is the feature of spring frame work by which we can achieved
“DI automatically.” or in other words we can say that Features of
spring framework in which spring container inject the
dependencies automatically.
• Autowiring can not be used to inject primitive and string values. It
work with reference only.
• Suppose we have two classes A and B. A needs to object of class
B.

Advantage & Disadvantage of Autowiring


Advantage
• It requires the less code because we don't need to write the code to
inject the dependency explicitly.
Disadvantage
• No control of programmer.
How to use autowiring
Two ways-:
• 1.by XML
• 2.Anotation

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

By XML file

Steps to create maven project


• Step1-: File Menu→New→Other→Maven Folder→Maven
Project
<?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="b" class="org.sssit.B"></bean>


<bean id="a" class="org.sssit.A" autowire="byName"></bean>

</beans>
2. By Annotation
• Using @Autowired
Used with 3 places
1. Used with Property
2. Used with Setter Method
3. Used with Constructor

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Java Annotations
Java Annotation is a tag that represents the metadata i.e. attached with class, interface,
methods or fields to indicate some additional information which can be used by java
compiler and JVM.

Annotations in Java are used to provide additional information, so it is an alternative


option for XML and Java marker interfaces.

First, we will learn some built-in annotations then we will move on creating and using
custom annotations.

Built-In Java Annotations


There are several built-in annotations in Java. Some annotations are applied to Java code
and some to other annotations.

Built-In Java Annotations used in Java code


o @Override
o @SuppressWarnings
o @Deprecated

Built-In Java Annotations used in other annotations


o @Target
o @Retention
o @Inherited
o @Documented

Understanding Built-In Annotations


@Override

@Override annotation assures that the subclass method is overriding the parent class
method. If it is not so, compile time error occurs.

Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark
@Override annotation that provides assurity that method is overridden.

class Animal{

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

void eatSomething(){System.out.println("eating something");}


}

class Dog extends Animal{


@Override
void eatsomething(){System.out.println("eating foods");}//should be eatSomething
}

class TestAnnotation1{
public static void main(String args[]){
Animal a=new Dog();
a.eatSomething();
}}

@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.

import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
public static void main(String args[]){
ArrayList list=new ArrayList();
list.add("sonoo");
list.add("vimal");
list.add("ratan");

for(Object obj:list)
System.out.println(obj);

}}

If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at


compile time because we are using non-generic collection.

@Deprecated

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

@Deprecated annoation marks that this method is deprecated so compiler prints


warning. It informs user that it may be removed in the future versions. So, it is better not
to use such methods.

class A{
void m(){System.out.println("hello m");}

@Deprecated
void n(){System.out.println("hello n");}
}

class TestAnnotation3{
public static void main(String args[]){

A a=new A();
a.n();
}}
At Compile Time:
Note: Test.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.


At Runtime:
hello n

Java Custom Annotations

Java Custom annotations or Java User-defined annotations are easy to create and use.
The @interface element is used to declare an annotation. For example:

@interface MyAnnotation{}

Here, MyAnnotation is the custom annotation name.

Points to remember for java custom annotation signature


There are few points that should be remembered by the programmer.
1. Method should not have any throws clauses
2. Method should return one of the following: primitive data types, String, Class, enum or
array of these data types.
3. Method should not have any parameter.
4. We should attach @ just before interface keyword to define annotation.
5. It may assign a default value to the method.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Types of Annotation
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation

1) Marker Annotation
ADVERTISEMENT

An annotation that has no method, is called marker annotation. For example:

@interface MyAnnotation{}

The @Override and @Deprecated are marker annotations.

2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:

@interface MyAnnotation{
int value();
}

We can provide the default value also. For example:

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

@interface MyAnnotation{
int value() default 0;
}
How to apply Single-Value Annotation
@MyAnnotation(value=10)

The value can be anything.

3) Multi-Value Annotation

An annotation that has more than one method, is called Multi-Value annotation. For
example:

@interface MyAnnotation{
int value1();
String value2();
String value3();
}}
We can provide the default value also. For example:
@interface MyAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}
How to apply Multi-Value Annotation
@MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

What is Spring Boot

Spring Boot is a project that is built on the top of the Spring Framework. It provides an
easier and faster way to set up, configure, and run both simple and web-based
applications.
It is a Spring module that provides the RAD (Rapid Application Development) feature
to the Spring Framework. It is used to create a stand-alone Spring-based application that
you can just run because it needs minimal Spring configuration.

In short, Spring Boot is the combination of Spring Framework and Embedded Servers.

In Spring Boot, there is no requirement for XML configuration (deployment descriptor). It


uses convention over configuration software design paradigm that means it decreases
the effort of the developer.

We can use Spring STS IDE or Spring Initializr to develop Spring Boot Java applications.

Why should we use Spring Boot Framework?

We should use Spring Boot Framework because:

o The dependency injection approach is used in Spring Boot.


o It contains powerful database transaction management capabilities.
o It simplifies integration with other Java frameworks like JPA/Hibernate ORM, Struts, etc.
o It reduces the cost and development time of the application.

There are the following Spring sister projects are as follows:

o Spring Data: It simplifies data access from the relational and NoSQL databases.
o Spring Batch: It provides powerful batch processing.
o Spring Security: It is a security framework that provides robust security to applications.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

o Spring Social: It supports integration with social networking like LinkedIn.


o Spring Integration: It is an implementation of Enterprise Integration Patterns. It facilitates
integration with other enterprise applications using lightweight messaging and
declarative adapters.

Advantages of Spring Boot


o It creates stand-alone Spring applications that can be started using Java -jar.
o It tests web applications easily with the help of different Embedded HTTP servers such
as Tomcat, Jetty, etc. We don't need to deploy WAR files.
o It provides opinionated 'starter' POMs to simplify our Maven configuration.
o It provides production-ready features such as metrics, health checks, and externalized
configuration.
o There is no requirement for XML configuration.
o It offers a CLI tool for developing and testing the Spring Boot application.
o It offers the number of plug-ins.
o It also minimizes writing multiple boilerplate codes (the code that has to be included in
many places with little or no alteration), XML configuration, and annotations.
o It increases productivity and reduces development time.

Goals of Spring Boot


The main goal of Spring Boot is to reduce development, unit test, and integration
test time.

o Provides Opinionated Development approach


o Avoids defining more Annotation Configuration
o Avoids writing lots of import statements
o Avoids XML Configuration.

By providing or avoiding the above points, Spring Boot Framework


reduces Development time, Developer Effort, and increases productivity.

Spring Boot Features


o Web Development

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

o SpringApplication
o Application events and listeners
o Admin features
o Externalized Configuration
o Properties Files
o YAML Support
o Type-safe Configuration
o Logging
o Security

Spring vs. Spring Boot


Spring Spring Boot

Spring Framework is a widely used Java EE Spring Boot Framework is widely used to
framework for building applications. develop REST APIs.

It aims to simplify Java EE development that It aims to shorten the code length and provide
makes developers more productive. the easiest way to develop Web Applications.

The primary feature of the Spring Framework The primary feature of Spring Boot
is dependency injection. is Autoconfiguration. It automatically
configures the classes based on the requirement.

It helps to make things simpler by allowing us It helps to create a stand-alone application with
to develop loosely coupled applications. less configuration.

To test the Spring project, we need to set up the Spring Boot offers embedded server such
sever explicitly. as Jetty and Tomcat, etc.

It does not provide support for an in-memory It offers several plugins for working with an
database. embedded and in-memory database such
as H2.

Spring Boot vs. Spring MVC


Spring Boot Spring MVC

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Spring Boot is a module of Spring for Spring MVC is a model view


packaging the Spring-based application with controller-based web framework
sensible defaults. under the Spring framework.

It provides default configurations to It provides ready to use features for


build Spring-powered framework. building a web application.

There is no need to build configuration It requires build configuration


manually. manually.

There is no requirement for a deployment A Deployment descriptor is required.


descriptor.

It avoids boilerplate code and wraps It specifies each dependency


dependencies together in a single unit. separately.

It reduces development time and increases It takes more time to achieve the
productivity. same.

Spring Boot Architecture

There are four layers in Spring Boot are as follows:

o Presentation Layer
o Business Layer
o Persistence Layer
o Database Layer

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Presentation Layer: The presentation layer handles the HTTP requests, translates the
JSON parameter to object, and authenticates the request and transfer it to the business
layer. In short, it consists of views i.e., frontend part.

Business Layer: The business layer handles all the business logic. It consists of service
classes and uses services provided by data access layers. It also
performs authorization and validation.

Persistence Layer: The persistence layer contains all the storage logic and translates
business objects from and to database rows.

Database Layer: In the database layer, CRUD (create, retrieve, update, delete) operations
are performed.

Spring Boot Flow Architecture

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Spring Boot - Code Structure


Spring Boot does not have any code layout to work with. However, there are some
best practices that will help us. This chapter talks about them in detail.

Default package

A class that does not have any package declaration is considered as a default
package. Note that generally a default package declaration is not recommended.
Spring Boot will cause issues such as malfunctioning of Auto Configuration or
Component Scan, when you use default package.

Note − Java's recommended naming convention for package declaration is reversed


domain name. For example − com.tutorialspoint.myproject

Typical Layout

The typical layout of Spring Boot application is shown in the image given below −

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

The Application.java file should declare the main method along with
@SpringBootApplication. Observe the code given below for a better understanding −

package com.tutorialspoint.myproject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
public static void main(String[] args) {SpringApplication.run(Application.class,
args);}
}
Spring Boot - Runners
Application Runner and Command Line Runner interfaces lets you to execute the
code after the Spring Boot application is started. You can use these interfaces to
perform any actions immediately after the application has started. This chapter talks
about them in detail.

Application Runner

Application Runner is an interface used to execute the code after the Spring Boot
application started. The example given below shows how to implement the
Application Runner interface on the main class file.

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

package com.tutorialspoint.demo;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("Hello World from Application Runner");
}
}

Now, if you observe the console window below Hello World from Application
Runner, the println statement is executed after the Tomcat started

Command Line Runner


Command Line Runner is an interface. It is used to execute the code after the Spring Boot
application started. The example given below shows how to implement the Command Line
Runner interface on the main class file.

package com.tutorialspoint.demo;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... arg0) throws Exception {
System.out.println("Hello world from Command Line Runner");
}
}

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Look at the console window below “Hello world from Command Line Runner” println statement
is executed after the Tomcat started.

Spring Boot - Logging


Spring Boot uses Apache Commons logging for all internal logging. Spring Boot’s
default configurations provides a support for the use of Java Util Logging, Log4j2,
and Logback. Using these, we can configure the console logging as well as file
logging.

If you are using Spring Boot Starters, Logback will provide a good support for
logging. Besides, Logback also provides a use of good support for Common Logging,
Util Logging, Log4J, and SLF4J.

Log Format

The default Spring Boot Log format is shown in the screenshot given below.

which gives you the following information −

• Date and Time that gives the date and time of the log
• Log level shows INFO, ERROR or WARN
• Process ID
• The --- which is a separator
• Thread name is enclosed within the square brackets []
• Logger Name that shows the Source class name
• The Log message

Spring Boot - Building RESTful Web Services


1. Spring Boot Starter: Provides a fast way to set up a Spring application with sensible
defaults.
2. Controller: Defines endpoints and handles HTTP requests.
3. Service: Contains business logic.
4. Repository: Manages data access.

Steps to Create a RESTful Web Service

1. Create a Spring Boot Project: Use Spring Initializr or an IDE to create a new Spring
Boot project with dependencies for Spring Web.
2. Define the Application Entry Point: This class starts the Spring application.

java

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

Copy code
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {


SpringApplication.run(DemoApplication.class, args);
}
}

3. Create a Model: Represents the data structure.

java
Copy code
package com.example.demo.model;

public class Greeting {

private long id;


private String content;

public Greeting(long id, String content) {


this.id = id;
this.content = content;
}

// Getters and Setters


}

4. Create a Service: Contains business logic.

java
Copy code
package com.example.demo.service;

import org.springframework.stereotype.Service;
import com.example.demo.model.Greeting;

@Service
public class GreetingService {

public Greeting getGreeting(long id, String name) {

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

return new Greeting(id, "Hello, " + name + "!");


}
}

5. Create a Controller: Handles HTTP requests.

java
Copy code
package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.Greeting;
import com.example.demo.service.GreetingService;

@RestController
public class GreetingController {

@Autowired
private GreetingService greetingService;

@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World")
String name) {
return greetingService.getGreeting(1, name);
}
}

6. Run the Application: Use mvn spring-boot:run or run the main method in
DemoApplication.

Example Request

• URL: http://localhost:8080/greeting?name=John
• Response:

json
Copy code
{
"id": 1,
"content": "Hello, John!"
}
What is RestController

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

RestController: RestController is used for making restful web services with the help of the
@RestController annotation. This annotation is used at the class level and allows the class to
handle the requests made by the client. Let’s understand @RestController annotation using an
example. The RestController allows to handle all REST APIs such
as GET, POST, Delete, PUT requests.

Step by Step Implementation

Step 1: Go to Spring Initializr


Step 2: Click on Generate which will download the starter project
Step 3: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from
existing sources > Spring-boot-app and select pom.xml.
Step 4: Go to src > main > java > com.gfg.Spring.boot.app, create a java class with the name
Controller and add the annotation @RestController and other class named as Details.
Details:

public class Details {

// Creating an object of ArrayList


static ArrayList<Details> Data = new ArrayList<Details>();
int number;
String name;
Details(int number, String name)
{
// This keyword refers
// to parent instance itself
this.number = number;
this.name = name;
}
}

Controller:

Java

@RestController
// Class
public class Controller {
// Constructor
Controller()
{
a.add(1);
a.add(2);

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

@GetMapping("/hello/{name}/{age}")
public void insert(@PathVariable("name") String name,
@PathVariable("age") int age)
{

// Print and display name and age


System.out.println(name);
System.out.println(age);
}

// Creating an empty ArrayList


ArrayList<Integer> a = new ArrayList<>();

// Annotation
@DeleteMapping("/hello/{id}")
// Method
public void deleteById(@PathVariable("id") int id)
{
a.remove(new Integer((id)));
print();
}

// Handling post request


@PostMapping("/EnterDetails")
String insert(@RequestBody Details ob)
{
// Storing the incoming data in the list
Data.add(new Details(ob.number, ob.name));

// Iterating using foreach loop


for (Details obd : Data) {
System.out.println(obd.name + " " + ob.number);
}
return "Data Inserted";
}

// Method
void print()
{
for (int elements : a) {
System.out.print(elements);
}
}

DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [Document title]

This application is now ready to run.


Step 5: Run the SpringBootAppApplication class and wait for the Tomcat server to start.

Mapping Requests
This section discusses request mapping for annotated controllers.
@RequestMapping

We can use the @RequestMapping annotation to map requests to controllers methods. It has
various attributes to match by URL, HTTP method, request parameters, headers, and media
types. You can use it at the class level to express shared mappings or at the method level to
narrow down to a specific endpoint mapping.
There are also HTTP method specific shortcut variants of @RequestMapping:
• @GetMapping
• @PostMapping
• @PutMapping
• @DeleteMapping
• @PatchMapping
Example:
@RestController
@RequestMapping("/persons")
class PersonController {

@GetMapping("/{id}")
public Person getPerson(@PathVariable Long id) {
// ...
}

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void add(@RequestBody Person person) {
// ...
}}

What is Request Body?

When you need to send data from a client (let's say, a browser) to your API, you send it as a
request body. A request body is data sent by the client to your API. A response body is the data
your API sends to the client. Your API almost always has to send a response body.
@RequestBody

@RequestBody is mainly used with CRUD Operations to read the request body.
Example:
@PostMapping("/addStudent")
public void AddStudent(@RequestBody Student student) {
// body}

DHANANJAYSHARMAOFFICIALS

You might also like