Java Spring Tutorial
Java Spring Tutorial
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.
Narrowing Casting double -> float -> long -> int -> char -
> short -> byte
Array
[Link](i);
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)).
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
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)
String
2 int compareTo(Object o)
Compares this String to another Object.
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 int hashCode()
5 Returns a hash code for this string.
2 int length()
5 Returns the length 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 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 trim()
5 Returns a copy of the string, with leading and trailing whitespace omit
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);
Returns true if the invoking Date object contains the same time
specified by date, otherwise, it returns false.
7 long getTime( )
Current DateTime
Date Comparison
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
Overloading
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.
Access Modifiers
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
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
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.
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
Inner Classes
OuterClass myOuter = new OuterClass();
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
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
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.
[Link]("Volvo");
[Link](0);
[Link](0, "Opel");
[Link](0);
[Link]();
[Link]();
[Link](cars);
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).
[Link]("England", "London");
[Link]("England"); [Link]("England");
[Link](); [Link]();
[Link](i);
}
HashSet
HashSet is a collection of items where every item is unique, and it is found in
the [Link] package:
[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]());
Exceptions
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
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
Expression Description
[abc] Find one character from the options between the brac
Metacharacter Description
\d Find a digit
Quantifier Description
[Link]();
Lambda Expressions
parameter -> expression
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
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
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
Deserializing an Object
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.
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.
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.
Bean Definition
All the above configuration metadata translates into a set of the following
properties that make up each bean definition.
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.
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
Destruction callbacks
The [Link] interface specifies
a single method −
</beans>
Dependency Injection
Constructor-based dependency injection
</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
</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.
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.
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.
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();
}
}
@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.
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.
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
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
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.