[Go to site: main page, start]

0% found this document useful (0 votes)
2 views39 pages

Java Spring Tutorial

Cherry Installments is a FinTech company that simplifies installment payments for direct-to-consumer businesses, aiming to enhance sales. The company is led by experienced Stanford entrepreneurs and backed by notable investors. They are currently seeking a Backend Engineer to join their Istanbul team, requiring expertise in Java, Spring Framework, microservices, and various database technologies.

Uploaded by

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

Java Spring Tutorial

Cherry Installments is a FinTech company that simplifies installment payments for direct-to-consumer businesses, aiming to enhance sales. The company is led by experienced Stanford entrepreneurs and backed by notable investors. They are currently seeking a Backend Engineer to join their Istanbul team, requiring expertise in Java, Spring Framework, microservices, and various database technologies.

Uploaded by

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

Cherry Installments is a FinTech company making it quick and simple for direct-

to-consumer businesses to grow their sales by offering installments as a


payment option.

We know that every sale counts. We believe everyone should have the tools to
win every sale. We hire the world’s best and brightest people to make this
future a reality.

Cherry is backed by an all-star lineup of investors such as DCM and early Tesla
board member and eBay Motors Founder Simon Rothman. Cherry was founded
and is led by Stanford entrepreneurs with years of experience in Technology,
Sales and Finance.

We are looking for an experienced Backend Engineer to join our growing


Istanbul-based Cherry Engineering Team! As a Backend Engineer, you will be
responsible for the server-side web application logic, development,
maintenance of various microservices, as well as for the integration of the
front-end part.

Java and Spring Framework, Kotlin,


OOP concepts, large-scale software architecture, networking, distributed
system, and UNIX/Linux environments, design principles for a scalable
application,
relational and non-relational databases, key-value stores, and search engines
(MySQL, MongoDB, Redis, Elasticsearch, etc.)
front-end technologies such as Javascript, HTML5, and CSS3
unit test and debugging skills
Service-oriented architecture, microservices, and REST APIs
Java
Java is case-sensitive
A class should always start with an uppercase first letter.
The name of the java file must match the class name.
every program must contain the main() method.
Widening Casting byte -> short -> char -> int -> long -
> float -> double
int myInt = 9;

double myDouble = myInt; // Automatic casting: int to


double

Narrowing Casting double -> float -> long -> int -> char -
> short -> byte

double myDouble = 9.78d;

int myInt = (int) myDouble; // Manual casting: double


to int

Array

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (String i : cars) {

[Link](i);

dataType[] arrayRefVar = new dataType[arraySize];

1 public static int binarySearch(Object[] a, Object key)

Searches the specified array of Object ( Byte, Int , double, etc.) for the
the binary search algorithm. The array must be sorted prior to making
index of the search key, if it is contained in the list; otherwise, it return
1)).

2 public static boolean equals(long[] a, long[] a2)

Returns true if the two specified arrays of longs are equal to one an
considered equal if both arrays contain the same number of elements,
pairs of elements in the two arrays are equal. This returns true if the
Same method could be used by all other primitive data types (Byte, sho

3 public static void fill(int[] a, int val)

Assigns the specified int value to each element of the specified arr
method could be used by all other primitive data types (Byte, short, Int
4 public static void sort(Object[] a)

Sorts the specified array of objects into an ascending order, acco


ordering of its elements. The same method could be used by all othe
( Byte, short, Int, etc.)

String

1 char charAt(int index)


Returns the character at the specified index.

2 int compareTo(Object o)
Compares this String to another Object.

3 int compareTo(String anotherString)


Compares two strings lexicographically.

4 int compareToIgnoreCase(String str)


Compares two strings lexicographically, ignoring case differences.

5 String concat(String str)


Concatenates the specified string to the end of this string.

6 boolean contentEquals(StringBuffer sb)


Returns true if and only if this String represents the same sequence
specified StringBuffer.

7 static String copyValueOf(char[] data)


Returns a String that represents the character sequence in the array s

8 static String copyValueOf(char[] data, int offset, int count)


Returns a String that represents the character sequence in the array s

9 boolean endsWith(String suffix)


Tests if this string ends with the specified suffix.

1 boolean equals(Object anObject)


0 Compares this string to the specified object.

1 boolean equalsIgnoreCase(String anotherString)


1 Compares this String to another String, ignoring case considerations.

1 byte[] getBytes()
2 Encodes this String into a sequence of bytes using the platform's de
the result into a new byte array.

1 byte[] getBytes(String charsetName)


3 Encodes this String into a sequence of bytes using the named char
into a new byte array.

1 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)


4 Copies characters from this string into the destination character array

1 int hashCode()
5 Returns a hash code for this string.

1 int indexOf(int ch)


6 Returns the index within this string of the first occurrence of the speci

1 int indexOf(int ch, int fromIndex)


7 Returns the index within this string of the first occurrence of the
starting the search at the specified index.

1 int indexOf(String str)


8 Returns the index within this string of the first occurrence of the speci

1 int indexOf(String str, int fromIndex)


9 Returns the index within this string of the first occurrence of the
starting at the specified index.
2 String intern()
0 Returns a canonical representation for the string object.

2 int lastIndexOf(int ch)


1 Returns the index within this string of the last occurrence of the speci

2 int lastIndexOf(int ch, int fromIndex)


2 Returns the index within this string of the last occurrence of the
searching backward starting at the specified index.

2 int lastIndexOf(String str)


3 Returns the index within this string of the rightmost occurrence of the

2 int lastIndexOf(String str, int fromIndex)


4 Returns the index within this string of the last occurrence of the
searching backward starting at the specified index.

2 int length()
5 Returns the length of this string.

2 boolean matches(String regex)


6 Tells whether or not this string matches the given regular expression.

2 boolean regionMatches(boolean ignoreCase, int toffset, String other, i


7 Tests if two string regions are equal.

2 boolean regionMatches(int toffset, String other, int ooffset, int len)


8 Tests if two string regions are equal.

2 String replace(char oldChar, char newChar)


9 Returns a new string resulting from replacing all occurrences of oldC
newChar.

3 String replaceAll(String regex, String replacement


0 Replaces each substring of this string that matches the given regula
given replacement.

3 String replaceFirst(String regex, String replacement)


1 Replaces the first substring of this string that matches the given re
the given replacement.

3 String[] split(String regex)


2 Splits this string around matches of the given regular expression.

3 String[] split(String regex, int limit)


3 Splits this string around matches of the given regular expression.

3 boolean startsWith(String prefix)


4 Tests if this string starts with the specified prefix.

3 boolean startsWith(String prefix, int toffset)


5 Tests if this string starts with the specified prefix beginning a specified

3 CharSequence subSequence(int beginIndex, int endIndex)


6 Returns a new character sequence that is a subsequence of this seque

3 String substring(int beginIndex)


7 Returns a new string that is a substring of this string.

3 String substring(int beginIndex, int endIndex)


8 Returns a new string that is a substring of this string.

3 char[] toCharArray()
9 Converts this string to a new character array.

4 String toLowerCase()
0 Converts all of the characters in this String to lower case using th
locale.

4 String toLowerCase(Locale locale)


1 Converts all of the characters in this String to lower case using th
Locale.

4 String toString()
2 This object (which is already a string!) is itself returned.

4 String toUpperCase()
3 Converts all of the characters in this String to upper case using th
locale.

4 String toUpperCase(Locale locale)


4 Converts all of the characters in this String to upper case using th
Locale.

4 String trim()
5 Returns a copy of the string, with leading and trailing whitespace omit

4 static String valueOf(primitive data type x)


6 Returns the string representation of the passed data type argument.

You have printf() and format() methods to print output with


formatted numbers.

[Link]("The value of the float variable is " +


"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);

You can write −

String fs;
fs = [Link]("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
[Link](fs);

Strings - Special Characters


\', \", \\, \n, \r(carriage return), \t, \b, \f(Form Feed)

Date and Time

6 boolean equals(Object date)

Returns true if the invoking Date object contains the same time
specified by date, otherwise, it returns false.

7 long getTime( )

Returns the number of milliseconds that have elapsed since January 1,

8 void setTime(long time)

Sets the time and date as specified by time, which represents


milliseconds from midnight, January 1, 1970.

Current DateTime

Date date = new Date();

// display time and date using toString()


[Link]([Link]());

Date Comparison

Following are the three ways to compare two dates −


 You can use getTime( ) to obtain the number of
milliseconds that have elapsed since midnight,
January 1, 1970, for both objects and then compare
these two values.
 You can use the methods before( ), after( ), and
equals( ). Because the 12th of the month comes
before the 18th, for example, new Date(99, 2,
12).before(new Date (99, 2, 18)) returns true.
 You can use the compareTo( ) method, which is
defined by the Comparable interface and
implemented by Date.
Date Formatting Using SimpleDateFormat

SimpleDateFormat is a concrete class for formatting and


parsing dates in a locale-sensitive manner. SimpleDateFormat
allows you to start by choosing any user-defined patterns for
date-time formatting.

String str = [Link]("Current Date/Time : %tc", date );


[Link]("%1$s %2$tB %2$td, %2$tY", "Due date:",
date);

SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");


String input = [Link] == 0 ? "1818-11-11" : args[0];
Date t = [Link](input);

static means that the method belongs to the Main class and
not an object of the Main class.
static method, which means that it can be accessed without
creating an object of the class

public static void main(String[] args) -> arguments

The void keyword, used in the examples above, indicates that


the method should not return a value.

Overloading

method overloading, multiple methods can have the same


name with different parameters

Java Recursion
Recursion is the technique of making a function call itself.
Halting Condition
OOP
The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of
code.
a class is a template for objects, and an object is an instance of a class.
A Class is like an object constructor, or a "blueprint" for creating objects.

final keyword is useful when you want a variable to always store


the same value, like PI
A constructor in Java is a special method that is used to initialize
objects. The constructor is called when an object of a class is
created. It can be used to set initial values for object attributes
Note that the constructor name must match the class name, and it
cannot have a return type (like void).

Access Modifiers

public The code is accessible for all classes

private The code is only accessible within the declared class

default The code is only accessible in the same package. This is used when you don't
the Packages chapter

protecte The code is accessible in the same package and subclasses. You will learn m
d chapter

Non-Access Modifiers
For classes, you can use either final or abstract:

Modifier Description

final The class cannot be inherited by other classes (You will learn more about inhe

abstract The class cannot be used to create objects (To access an abstract class, it must
and abstraction in the Inheritance and Abstraction chapters)

For attributes and methods, you can use the one of the following:

Modifier Description

final Attributes and methods cannot be overridden/modified

static Attributes and methods belongs to the class, rather than an object

abstract Can only be used in an abstract class, and can only be used on methods. The method do
subclass (inherited from). You will learn more about inheritance and abstraction in the I

transient Attributes and methods are skipped when serializing the object containing them

synchronized Methods can only be accessed by one thread at a time

volatile The value of an attribute is not cached thread-locally, and is always read from the "main

Java Packages
A package in Java is used to group related classes to write a better
maintainable code.

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

The library is divided into packages and classes.

import [Link]; //import class

import [Link].*; // import package


Encapsulation
 declare class variables/attributes as private
 provide public get and set methods to access and update the value of
a private variable
 Class attributes can be made read-only or write-only
 Flexible
 Increased security of data

Inheritance
 subclass (child) - the class that inherits from another class
 superclass (parent) - the class being inherited from
 To inherit from a class, use the extends keyword.
 It is useful for code reusability: reuse attributes and methods of an
existing class when you create a new class.

final The class cannot be inherited by other classes (You will learn more about inheritance in the I

Polymorphism
Inheritance lets us inherit attributes and methods from another
class. Polymorphism uses those methods to perform different
tasks. This allows us to perform a single action in different ways.

Virtual Methods

public interface Vegetarian{}


public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Inner Classes
OuterClass myOuter = new OuterClass();

[Link] myInner = [Link] InnerClass()


default,public

[Link] myInner = new [Link]();


static

Abstraction
abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces

 Abstract class: is a restricted class that cannot be used to create


objects (to access it, it must be inherited from another class).

 Abstract method: can only be used in an abstract class, and it does


not have a body. The body is provided by the subclass (inherited from).

Interface
An interface is a completely "abstract class" that is used to group
related methods with empty bodies
interfaces cannot be used to create objects

On implementation of an interface, you must override all of its methods

An interface cannot contain a constructor (as it cannot be used to create


objects)

Java does not support "multiple inheritance" (a class can only inherit from one
superclass). However, it can be achieved with interfaces, because the class
can implement multiple interfaces. Note: To implement multiple interfaces,
separate them with a comma (see example below).

Overriding
 The argument list should be exactly the same as that of the
overridden method.
 The return type should be the same or a subtype of the return
type declared in the original overridden method in the
superclass.
 The access level cannot be more restrictive than the
overridden method's access level. For example: If the
superclass method is declared public then the overridding
method in the sub class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited
by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-
declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's
superclass can override any superclass method that is not
declared private or final.
 A subclass in a different package can only override the non-
final methods declared public or protected.
 An overriding method can throw any uncheck exceptions,
regardless of whether the overridden method throws
exceptions or not. However, the overriding method should not
throw checked exceptions that are new or broader than the
ones declared by the overridden method. The overriding
method can throw narrower or fewer exceptions than the
overridden method.
 Constructors cannot be overridden.
 When invoking a superclass version of an overridden method
the super keyword is used.

User Input
The Scanner class is used to get user input, and it is found in
the [Link] package.

To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation with next
functions

ArrayList
The ArrayList class is a resizable array, which can be found in
the [Link] package.

ArrayList<String> cars = new ArrayList<String>();

[Link]("Volvo");

[Link](0);

[Link](0, "Opel");

[Link](0);

[Link]();

[Link]();

[Link](cars);

ArrayList vs. LinkedList


The LinkedList class has all of the same methods as
the ArrayList class because they both implement
the List interface. This means that you can add items, change
items, remove items and clear the list in the same way.

Use an ArrayList for storing and accessing data,


and LinkedList to manipulate data.
addFirst() Adds an item to the beginning of the list.

addLast() Add an item to the end of the list

removeFirst() Remove an item from the beginning of the list.

removeLast() Remove an item from the end of the list

getFirst() Get the item at the beginning of the list

getLast() Get the item at the end of the list

HashMap
A HashMap however, store items in "key/value" pairs, and you can access
them by an index of another type (e.g. a String).

HashMap<String, String> capitalCities = new HashMap<String,


String>();

[Link]("England", "London");

[Link]("England"); [Link]("England");

[Link](); [Link]();

for (String i : [Link]()) { // keySet for keys,


values for values

[Link](i);

}
HashSet
HashSet is a collection of items where every item is unique, and it is found in
the [Link] package:

HashSet<String> cars = new HashSet<String>();

[Link]("Volvo"); [Link]("Volvo"); [Link]();


[Link]();

[Link]("Mazda");

Iterator
Iterator is an object that can be used to loop through collections,
like ArrayList and HashSet

Iterator<String> it = [Link]();

while([Link]()) {

[Link]([Link]());

Wrapper classes provide a way to use primitive data types


(int, boolean, etc..) as objects.

ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid

ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid

Exceptions
The try statement allows you to define a block of code to be tested for errors
while it is being executed.

The catch statement allows you to define a block of code to be executed, if


an error occurs in the try block.

The finally statement lets you execute code, after try...catch

The throw statement allows you to create a custom error.

The throw statement is used together with an exception type.

Regular Expression
 Pattern Class - Defines a pattern (to be used in a search)
 Matcher Class - Used to search for the pattern
 Pattern.CASE_INSENSITIVE - The case of letters will be ignored when
performing a search.
 [Link] - Special characters in the pattern will not have any
special meaning and will be treated as ordinary characters when
performing a search.
 Pattern.UNICODE_CASE - Use it together with the CASE_INSENSITIVE flag to
also ignore the case of letters outside of the English alphabet

The first parameter of the [Link]() method is the pattern. It


describes what is being searched for.

Brackets are used to find a range of characters:

Expression Description

[abc] Find one character from the options between the brac

[^abc] Find one character NOT between the brackets

[0-9] Find one character from the range 0 to 9

Metacharacters are characters with a special meaning:

Metacharacter Description

| Find a match for any one of the patterns separated by

. Find just one instance of any character

^ Finds a match as the beginning of a string as in: ^Hel


$ Finds a match at the end of the string as in: World$

\d Find a digit

\s Find a whitespace character

\b Find a match at the beginning of a word like this: \bWO

\uxxxx Find the Unicode character specified by the hexadecim

Quantifiers define quantities:

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurre

n? Matches any string that contains zero or one occurren

n{x} Matches any string that contains a sequence of X n's

n{x,y} Matches any string that contains a sequence of X to Y

n{x,} Matches any string that contains a sequence of at leas


Threads
two ways to create a thread

public class Main extends Thread {

public void run() {

Main thread = new Main();

[Link]();

public class Main implements Runnable {

Lambda Expressions
parameter -> expression

(parameter1, parameter2) -> expression

(parameter1, parameter2) -> { code block }

[Link]( (n) -> { [Link](n); } );

Consumer<Integer> method = (n) -> { [Link](n); };

Files and I/O


InputStream − The InputStream is used to read data from a source.
OutputStream − The OutputStream is used for writing data to a
destination.

Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.

character streams but the most frequently used classes


are, FileReader and FileWriter.

 Standard Input − This is used to feed the data to user's


program and usually a keyboard is used as standard input
stream and represented as [Link].
 Standard Output − This is used to output the data produced
by the user's program and usually a computer screen is used
for standard output stream and represented as [Link].
 Standard Error − This is used to output the error data
produced by the user's program and usually a computer screen
is used for standard error stream and represented
as [Link].

InputStream f = new FileInputStream("C:/java/hello");


OutputStream f = new FileOutputStream("C:/java/hello")

 The mkdir( ) method creates a directory, returning true on


success and false on failure. Failure indicates that the path
specified in the File object already exists, or that the directory
cannot be created because the entire path does not exist yet.
 The mkdirs() method creates both a directory and all the
parents of the directory.
 you can use list( ) method provided by File object to list down
all the files and directories available in a directory
Collections Framework
1 The Collection Interface
This enables you to work with groups of objects; it is at the top of the collections hi

2 The List Interface


This extends Collection and an instance of List stores an ordered collection of elem

3 The Set
This extends Collection to handle sets, which must contain unique elements.

4 The SortedSet
This extends Set to handle sorted sets.

5 The Map
This maps unique keys to values.

6 The [Link]
This describes an element (a key/value pair) in a map. This is an inner class of Map

7 The SortedMap
This extends Map so that the keys are maintained in an ascending order.

8 The Enumeration
This is legacy interface defines the methods by which you can enumerate (ob
elements in a collection of objects. This legacy interface has been superceded by It

The Collection Classes

1
AbstractCollection
Implements most of the Collection interface.

2
AbstractList
Extends AbstractCollection and implements most of the List interface.

3
AbstractSequentialList
Extends AbstractList for use by a collection that uses sequential rather tha
elements.

4 LinkedList
Implements a linked list by extending AbstractSequentialList.

5 ArrayList
Implements a dynamic array by extending AbstractList.

6
AbstractSet
Extends AbstractCollection and implements most of the Set interface.

7 HashSet
Extends AbstractSet for use with a hash table.

8 LinkedHashSet
Extends HashSet to allow insertion-order iterations.

9 TreeSet
Implements a set stored in a tree. Extends AbstractSet.

10
AbstractMap
Implements most of the Map interface.
11 HashMap
Extends AbstractMap to use a hash table.

12 TreeMap
Extends AbstractMap to use a tree.

13 WeakHashMap
Extends AbstractMap to use a hash table with weak keys.

14 LinkedHashMap
Extends HashMap to allow insertion-order iterations.

15 IdentityHashMap
Extends AbstractMap and uses reference equality when comparing documents.

Generics
Generic Methods
 All generic method declarations have a type parameter section
delimited by angle brackets (< and >) that precedes the
method's return type ( < E > in the next example).
 Each type parameter section contains one or more type
parameters separated by commas. A type parameter, also
known as a type variable, is an identifier that specifies a
generic type name.
 The type parameters can be used to declare the return type
and act as placeholders for the types of the arguments passed
to the generic method, which are known as actual type
arguments.
 A generic method's body is declared like that of any other
method. Note that type parameters can represent only
reference types, not primitive types (like int, double and char).
 Generics also provide compile-time type safety

To declare a bounded type parameter, list the type parameter's name, followed by the
extends keyword, followed by its upper bound. public static <T extends
Comparable<T>> T maximum(T x, T y, T z)

Serialization
Classes ObjectInputStream and ObjectOutputStream are high-level
streams that contain the methods for serializing and deserializing an
object.
Notice that for a class to be serialized successfully, two conditions must be
met −
 The class must implement the [Link] interface.
 All of the fields in the class must be serializable. If a field is not
serializable, it must be marked transient.
Note − When serializing an object to a file, the standard convention in Java
is to give the file a .ser extension.

Serializing an Object

FileOutputStream, ObjectOutputStream, writeObject, close

Deserializing an Object

FileInputStream, ObjectInputStream, readObject, close

Multithreading
Following are the stages of the life cycle −
 New − A new thread begins its life cycle in the new state. It
remains in this state until the program starts the thread. It is
also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread
becomes runnable. A thread in this state is considered to be
executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state
while the thread waits for another thread to perform a task. A
thread transitions back to the runnable state only when
another thread signals the waiting thread to continue
executing.
 Timed Waiting − A runnable thread can enter the timed
waiting state for a specified interval of time. A thread in this
state transitions back to the runnable state when that time
interval expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the
terminated state when it completes its task or otherwise
terminates.
 Thread Methods
 Following is the list of important methods available in the Thread
class.

Sr.N Method & Description


o.

1
public void start()
Starts the thread in a separate path of execution, then invokes the run() metho

2
public void run()
If this Thread object was instantiated using a separate Runnable target, the ru
that Runnable object.

3
public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for

4
public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 1

5
public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.

6
public final void join(long millisec)
The current thread invokes this method on a second thread, causing the cur
the second thread terminates or the specified number of milliseconds passes.

7
public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any

8
public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been
to completion.

 The previous methods are invoked on a particular Thread object. The


following methods in the Thread class are static. Invoking one of the
static methods performs the operation on the currently running
thread.

Sr.N Method & Description


o.

1
public static void yield()
Causes the currently running thread to yield to any other threads of the same p
be scheduled.

2
public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number o

3
public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object.

4
public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that in

5
public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when de
application.

Spring
Core Container
The Core Container consists of the Core, Beans, Context, and Expression
Language modules the details of which are as follows −
 The Core module provides the fundamental parts of the
framework, including the IoC and Dependency Injection
features.
 The Bean module provides BeanFactory, which is a
sophisticated implementation of the factory pattern.
 The Context module builds on the solid base provided by the
Core and Beans modules and it is a medium to access any
objects defined and configured. The ApplicationContext
interface is the focal point of the Context module.
 The SpEL module provides a powerful expression language for
querying and manipulating an object graph at runtime.

Data Access/Integration
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS
and Transaction modules whose detail is as follows −
 The JDBC module provides a JDBC-abstraction layer that
removes the need for tedious JDBC related coding.
 The ORM module provides integration layers for popular
object-relational mapping APIs, including JPA, JDO, Hibernate,
and iBatis.
 The OXM module provides an abstraction layer that supports
Object/XML mapping implementations for JAXB, Castor,
XMLBeans, JiBX and XStream.
 The Java Messaging Service JMS module contains features for
producing and consuming messages.
 The Transaction module supports programmatic and
declarative transaction management for classes that
implement special interfaces and for all your POJOs.

Web
The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-
Portlet modules the details of which are as follows −
 The Web module provides basic web-oriented integration
features such as multipart file-upload functionality and the
initialization of the IoC container using servlet listeners and a
web-oriented application context.
 The Web-MVC module contains Spring's Model-View-Controller
(MVC) implementation for web applications.
 The Web-Socket module provides support for WebSocket-
based, two-way communication between the client and the
server in web applications.
 The Web-Portlet module provides the MVC implementation to
be used in a portlet environment and mirrors the functionality
of Web-Servlet module.

Miscellaneous
There are few other important modules like AOP, Aspects, Instrumentation,
Web and Test modules the details of which are as follows −
 The AOP module provides an aspect-oriented programming
implementation allowing you to define method-interceptors
and pointcuts to cleanly decouple code that implements
functionality that should be separated.
 The Aspects module provides integration with AspectJ, which
is again a powerful and mature AOP framework.
 The Instrumentation module provides class instrumentation
support and class loader implementations to be used in certain
application servers.
 The Messaging module provides support for STOMP as the
WebSocket sub-protocol to use in applications. It also supports
an annotation programming model for routing and processing
STOMP messages from WebSocket clients.
 The Test module supports the testing of Spring components
with JUnit or TestNG frameworks.
IoC Containers
Sr.N Container & Description
o.

1 Spring BeanFactory Container


This is the simplest container providing the basic support for D
the [Link] interface. The BeanFactor
such as BeanFactoryAware, InitializingBean, DisposableBean, are still present
of backward compatibility with a large number of third-party frameworks that in

2 Spring ApplicationContext Container


This container adds more enterprise-specific functionality such as the a
messages from a properties file and the ability to publish application ev
listeners. This container is defined by the [Link]

Bean Definition
All the above configuration metadata translates into a set of the following
properties that make up each bean definition.

Sr.N Properties & Description


o.

1
class
This attribute is mandatory and specifies the bean class to be used to create th

2
name
This attribute specifies the bean identifier uniquely. In XMLbased configuration
and/or name attributes to specify the bean identifier(s).

3
scope
This attribute specifies the scope of the objects created from a particular bea
discussed in bean scopes chapter.

4
constructor-arg
This is used to inject the dependencies and will be discussed in subsequent cha

5
properties
This is used to inject the dependencies and will be discussed in subsequent cha

6
autowiring mode
This is used to inject the dependencies and will be discussed in subsequent cha

7
lazy-initialization mode
A lazy-initialized bean tells the IoC container to create a bean instance when i
than at the startup.

8
initialization method
A callback to be called just after all necessary properties on the bean have bee
will be discussed in bean life cycle chapter.

9
destruction method
A callback to be used when the container containing the bean is destroyed. It
life cycle chapter.

Following are the three important methods to provide configuration


metadata to the Spring Container −

 XML based configuration file.


 Annotation-based configuration
 Java-based configuration
Bean Scopes
1
singleton
This scopes the bean definition to a single instance per Spring IoC container (defau

2
prototype
This scopes a single bean definition to have any number of object instances.

3
request
This scopes a bean definition to an HTTP request. Only valid in the context
ApplicationContext.

4
session
This scopes a bean definition to an HTTP session. Only valid in the context of a web-aw
ApplicationContext.

5
global-session
This scopes a bean definition to a global HTTP session. Only valid in the contex
ApplicationContext.

Initialization callbacks
The [Link] interface specifies a single
method

public class ExampleBean implements InitializingBean {


public void afterPropertiesSet() {
// do some initialization work
}
}

Destruction callbacks
The [Link] interface specifies
a single method −

public class ExampleBean implements DisposableBean {


public void destroy() {
// do some destruction work
}
}
Config
default-init-method = "init"
default-destroy-method = "destroy"

Bean Definition Inheritance

Bean Definition Template


You can create a Bean definition template, which can be used by other
child bean definitions without putting much effort. While defining a Bean
Definition Template, you should not specify the class attribute and should
specify abstract attribute and should specify the abstract attribute with a
value of true as shown in the following code snippet −

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


<beans xmlns = "[Link]
xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]

<bean id = "beanTeamplate" abstract = "true">


<property name = "message1" value = "Hello World!"/>
<property name = "message2" value = "Hello Second World!"/>
<property name = "message3" value = "Namaste India!"/>
</bean>

<bean id = "helloIndia" class = "[Link]" parent =


"beanTeamplate">
<property name = "message1" value = "Hello India!"/>
<property name = "message3" value = "Namaste India!"/>
</bean>

</beans>

Dependency Injection
Constructor-based dependency injection

public class TextEditor {


private SpellChecker spellChecker;

public TextEditor(SpellChecker spellChecker) {


[Link]("Inside TextEditor constructor." );
[Link] = spellChecker;
}
public void spellCheck() {
[Link]();
}
}
public class SpellChecker {
public SpellChecker(){
[Link]("Inside SpellChecker constructor." );
}
public void checkSpelling() {
[Link]("Inside checkSpelling." );
}
}

Setter-based dependency injection


public class TextEditor {
private SpellChecker spellChecker;

// a setter method to inject the dependency.


public void setSpellChecker(SpellChecker spellChecker) {
[Link]("Inside setSpellChecker." );
[Link] = spellChecker;
}
// a getter method to return spellChecker
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void spellCheck() {
[Link]();
}
}
public class SpellChecker {
public SpellChecker(){
[Link]("Inside SpellChecker constructor." );
}
public void checkSpelling() {
[Link]("Inside checkSpelling." );
}
}

Injecting Inner Beans


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

<beans xmlns = "[Link]


xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]

<bean id = "outerBean" class = "...">


<property name = "target">
<bean id = "innerBean" class = "..."/>
</property>
</bean>

</beans>

Injecting Collection
1
<list>
This helps in wiring ie injecting a list of values, allowing duplicates.

2
<set>
This helps in wiring a set of values but without any duplicates.

3
<map>
This can be used to inject a collection of name-value pairs where name and value c

4
<props>
This can be used to inject a collection of name-value pairs where the name and va

Injecting Bean References

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

<beans xmlns = "[Link]


xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link]

<!-- Bean Definition to handle references and values -->


<bean id = "..." class = "...">

<!-- Passing bean reference for [Link] -->


<property name = "addressList">
<list>
<ref bean = "address1"/>
<ref bean = "address2"/>
<value>Pakistan</value>
</list>
</property>

<!-- Passing bean reference for [Link] -->


<property name = "addressSet">
<set>
<ref bean = "address1"/>
<ref bean = "address2"/>
<value>Pakistan</value>
</set>
</property>

<!-- Passing bean reference for [Link] -->


<property name = "addressMap">
<map>
<entry key = "one" value = "INDIA"/>
<entry key = "two" value-ref = "address1"/>
<entry key = "three" value-ref = "address2"/>
</map>
</property>
</bean>

</beans>

Auto-Wiring
Spring container can autowire relationships between collaborating beans
without using <constructor-arg> and <property> elements, which helps cut
down on the amount of XML configuration you write for a big Spring-based
application.

Autowiring Modes

Following are the autowiring modes, which can be used to instruct the
Spring container to use autowiring for dependency injection. You use the
autowire attribute of the <bean/> element to specify autowire mode for
a bean definition.

Sr.N Mode & Description


o

1 no
This is default setting which means no autowiring and you should use explicit b
You have nothing to do special for this wiring. This is what you already ha
Injection chapter.

2 byName
Autowiring by property name. Spring container looks at the proper
which autowire attribute is set to byName in the XML configuration file. It then t
properties with the beans defined by the same names in the configuration file.

3 byType
Autowiring by property datatype. Spring container looks at the prope
which autowire attribute is set to byType in the XML configuration file. It then
property if its type matches with exactly one of the beans name in configurat
such beans exists, a fatal exception is thrown.

4 constructor
Similar to byType, but type applies to constructor arguments. If there is not
constructor argument type in the container, a fatal error is raised.

5 autodetect
Spring first tries to wire using autowire by constructor, if it does not work,
by byType.

Annotation Based Configuration


1 @Required
The @Required annotation applies to bean property setter methods.

2 @Autowired
The @Autowired annotation can apply to bean property setter methods, non-set
and properties.

3 @Qualifier
The @Qualifier annotation along with @Autowired can be used to remove the confu
exact bean will be wired.

Java Based Configuration

@Configuration & @Bean Annotations

Annotating a class with the @Configuration indicates that the class can
be used by the Spring IoC container as a source of bean definitions.
The @Bean annotation tells Spring that a method annotated with @Bean
will return an object that should be registered as a bean in the Spring
application context. The simplest possible @Configuration class would be
as follows −

package [Link];
import [Link].*;

@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}

ApplicationContext ctx = new


AnnotationConfigApplicationContext([Link]);
HelloWorld helloWorld = [Link]([Link]);
[Link]("Hello World!");
[Link]();
AnnotationConfigApplicationContext ctx = new
AnnotationConfigApplicationContext();
[Link]([Link], [Link]);
[Link]([Link]);
[Link]();

MyService myService = [Link]([Link]);


[Link]();

The @Import Annotation


The @Import annotation allows for loading
@Bean definitions from another
configuration class.
@Configuration
@Import([Link])
public class ConfigB {
@Bean
public B b() {

Lifecycle Callbacks & Scope


The @Bean annotation supports specifying arbitrary initialization and
destruction callback methods, much like Spring XML's init-method and
destroy-method attributes on the bean element −

@Configuration
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "cleanup" )
@Scope("prototype")
public Foo foo() {

Transaction Management
ACID −
 Atomicity − A transaction should be treated as a single unit of
operation, which means either the entire sequence of
operations is successful or unsuccessful.
 Consistency − This represents the consistency of the
referential integrity of the database, unique primary keys in
tables, etc.
 Isolation − There may be many transaction processing with
the same data set at the same time. Each transaction should
be isolated from others to prevent data corruption.
 Durability − Once a transaction has completed, the results of
this transaction have to be made permanent and cannot be
erased from the database due to system failure.

1
TransactionStatus getTransaction(TransactionDefinition definition)
This method returns a currently active transaction or creates a new one, ac
propagation behavior.

2
void commit(TransactionStatus status)
This method commits the given transaction, with regard to its status.

3
void rollback(TransactionStatus status)
This method performs a rollback of the given transaction.

The TransactionDefinition is the core interface of the transaction support in


Spring and it is defined as follows –

Sr.N Method & Description


o

1
int getPropagationBehavior()
This method returns the propagation behavior. Spring offers all of the transa
familiar from EJB CMT.

2
int getIsolationLevel()
This method returns the degree to which this transaction is isolated from the wo

3
String getName()
This method returns the name of this transaction.

4
int getTimeout()
This method returns the time in seconds in which the transaction must complet
5
boolean isReadOnly()
This method returns whether the transaction is read-only.

[Link] Isolation & Description

1
TransactionDefinition.ISOLATION_DEFAULT
This is the default isolation level.

2
TransactionDefinition.ISOLATION_READ_COMMITTED
Indicates that dirty reads are prevented; non-repeatable reads and phantom r

3
TransactionDefinition.ISOLATION_READ_UNCOMMITTED
Indicates that dirty reads, non-repeatable reads, and phantom reads can occu

4
TransactionDefinition.ISOLATION_REPEATABLE_READ
Indicates that dirty reads and non-repeatable reads are prevented; phantom r

5
TransactionDefinition.ISOLATION_SERIALIZABLE
Indicates that dirty reads, non-repeatable reads, and phantom reads are prev

[Link] Propagation & Description


.

1
TransactionDefinition.PROPAGATION_MANDATORY
Supports a current transaction; throws an exception if no current transaction e

2
TransactionDefinition.PROPAGATION_NESTED
Executes within a nested transaction if a current transaction exists.

3
TransactionDefinition.PROPAGATION_NEVER
Does not support a current transaction; throws an exception if a current trans

4
TransactionDefinition.PROPAGATION_NOT_SUPPORTED
Does not support a current transaction; rather always execute nontransaction

5
TransactionDefinition.PROPAGATION_REQUIRED
Supports a current transaction; creates a new one if none exists.

6
TransactionDefinition.PROPAGATION_REQUIRES_NEW
Creates a new transaction, suspending the current transaction if one exists.

7
TransactionDefinition.PROPAGATION_SUPPORTS
Supports a current transaction; executes non-transactionally if none exists.

8
TransactionDefinition.TIMEOUT_DEFAULT
Uses the default timeout of the underlying transaction system, or none if time

TransactionStatus interface provides a simple way for transactional code to


control transaction execution and query transaction status.

Sr.N Method & Description


o.

1
boolean hasSavepoint()
This method returns whether this transaction internally carries a savepoint,
nested transaction based on a savepoint.

2
boolean isCompleted()
This method returns whether this transaction is completed, i.e., whether it has
or rolled back.

3
boolean isNewTransaction()
This method returns true in case the present transaction is new.

4
boolean isRollbackOnly()
This method returns whether the transaction has been marked as rollback-only

5
void setRollbackOnly()
This method sets the transaction as rollback-only.

You might also like