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

Java Question Bank(2)

The document discusses wildcards and generics in Java, explaining the types of wildcards (upper bounded, lower bounded, and unbounded) and their usage in generic programming. It also covers the Java Collections Framework, detailing its components, interfaces, and classes, including the Map interface and its implementations like HashMap, LinkedHashMap, and TreeMap. Additionally, it introduces lambda expressions, their structure, and the concept of target typing in functional interfaces.

Uploaded by

khiljitantra
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 Question Bank(2)

The document discusses wildcards and generics in Java, explaining the types of wildcards (upper bounded, lower bounded, and unbounded) and their usage in generic programming. It also covers the Java Collections Framework, detailing its components, interfaces, and classes, including the Map interface and its implementations like HashMap, LinkedHashMap, and TreeMap. Additionally, it introduces lambda expressions, their structure, and the concept of target typing in functional interfaces.

Uploaded by

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

Q1.

Write short note of wildcards

ans The question mark (?) is known as the wildcard in generic programming. It
represents an unknown type. The wildcard can be used in a variety of situations such
as the type of a parameter, field, or local variable; sometimes as a return type. Unlike
arrays, different instantiations of a generic type are not compatible with each other,
not even explicitly. This incompatibility may be softened by the wildcard if ? is used
as an actual type parameter.

Type of wildcards in java


1. Upper Bounded wildcard
These wildcards can be used when you want to relax the restrictions on a variable.
For example, say you want to write a method that works on List < Integer >, List <
Double >, and List < Number >, you can do this using an upper bounded wildcard.
To declare an upper-bounded wildcard, use the wildcard character (‘?’), followed by
the extends keyword, followed by its upper bound.
public static void add(List<? extends Number> list)
2. Lower bounded wildcard
It is expressed using the wildcard character (‘?’), followed by the super keyword,
followed by its lower bound: <? super A>.
Syntax: Collectiontype <? super A>
3. Unbounded wildcard
This wildcard type is specified using the wildcard character (?), for example, List.
This is called a list of unknown types. These are useful in the following cases –
● When writing a method that can be employed using functionality
provided in Object class.
● When the code is using methods in the generic class that doesn’t depend
on the type parameter

Q2 Write short note on generic

ans Generics means parameterized types. The idea is to allow type (Integer, String, …
etc., and user-defined types) to be a parameter to methods, classes, and interfaces.
Using Generics, it is possible to create classes that work with different data types. An
entity such as class, interface, or method that operates on a parameterized type is a
generic entity.

Why generics?
The Object is the superclass of all other classes, and Object reference can refer to
any object. These features lack type safety. Generics add that type of safety feature.
Generics in Java are similar to templates in C++. For example, classes like HashSet,
ArrayList, HashMap, etc., use generics very well. There are some fundamental
differences between the two approaches to generic types.
Types of java generic
1. Generic methods
Generic Java method takes a parameter and returns some value after
performing a task. It is exactly like a normal function, however, a generic
method has type parameters that are cited by actual type. This allows the
generic method to be used in a more general way. The compiler takes care of
the type of safety which enables programmers to code easily since they do
not have to perform long, individual type castings.
2. Generic classes
A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than
one type of parameter, separated by a comma. The classes, which accept one
or more parameters, ​are known as parameterized classes or parameterized
types.
3. Generic functions
We can also write generic functions that can be called with different types of
arguments based on the type of arguments passed to the generic method. The
compiler handles each method.
Generic only works with reference type
When we declare an instance of a generic type, the type argument passed to the type
parameter must be a reference type. We cannot use primitive data types like int, char.
Test<int> obj = new Test<int>(20);
The above line results in a compile-time error that can be resolved using type
wrappers to encapsulate a primitive type.
But primitive type arrays can be passed to the type parameter because arrays are
reference types.
ArrayList<int[]> a = new ArrayList<>();
Advantages of generic
1. Code Reuse: We can write a method/class/interface once and use it for any type
we want.
2. Type Safety: Generics make errors to appear compile time than at run time (It’s
always better to know problems in your code at compile time rather than making
your code fail at run time). Suppose you want to create an ArrayList that store name
of students, and if by mistake the programmer adds an integer object instead of a
string, the compiler allows it. But, when we retrieve this data from ArrayList, it
causes problems at runtime.
3. Individual Type Casting is not needed: If we do not use generics, then, in the
above example, every time we retrieve data from ArrayList, we have to typecast it.
Typecasting at every retrieval operation is a big headache. If we already know that
our list only holds string data, we need not typecast it every time.
4. Generics Promotes Code Reusability: With the help of generics in Java, we can
write code that will work with different types of data.For example,
public <T> void genericsMethod (T data) {...}
Here, we have created a generics method. This same method can be used to perform
operations on integer data, string data, and so on.
5. Implementing Generic Algorithms: By using generics, we can implement
algorithms that work on different types of objects, and at the same, they are type-safe
too.

Q3 Write short note on collection framework

ans ● Collections framework provide two things:


○ Implementations of common high-level data structures. Eg. Map, set,
list, queue.
○ An organised class hierarchy with rule/formality for adding new
implementations
● The latter point is the sense in which Collections are a framework.
● Note the difference between providing a framework + implementation and
just implementation.
● Some other differences:
○ code reuse
○ Clarity
○ unit testing?
Definition of collection
● A collection — sometimes called a container — is simply an object that
groups multiple elements into a single unit.
● Collections are used to store, retrieve, manipulate, and communicate
aggregate data.
● They typically represent data items that form a natural group, e.g.
○ poker hand (a collection of cards), a mail folder (a collection of
letters), or a telephone directory (a mapping from names to phone
numbers).

Intro of collection framework


Java collection framework which is included in the Java platform and it is the
representation of a group of objects such as the classic Vector class, Array List, Hash
Map, Hash Set and even other collections framework is a unifying architecture for
describing and manipulating the collections that allowed for them to be modified
with regardless of implementation details that provides an architecture for storing
and manipulating a collection of objects it capable of doing any data operations such
as searching, sorting, insertion, manipulation, and deletion even single unit of objects
in Java is referred to as a collection.

Java collection framework components


With the support of key interfaces, the Collections framework is easier to grasp.
These interfaces are implemented and concrete functionality is provided by the
collections classes. The interface for collecting data is at the top of the hierarchy. All
general-purpose methods that all collections classes must provide are provided by the
Collection interface or throw an error like “UnsupportedOperationException”. It
adds some functionality for iterating with over-collection elements by using the
“for-each loop” statement to the Iterable interface. Except for the Map interface and
all other collection interfaces, classes extend to implement this interface. This
collection is implemented by the List (indexed, ordered) and Set (sorted) interfaces,
Map(key, value) pairs.

Interface
It’s one of the collection components that can be abstract with a data type to
represent the collection. The framework’s root interface in java.util.Collection by
using this import the significant class of the framework, with some default methods
like add(), remove(), size() etc. Mainly it has below default interfaces like Map, Set
and Deque all come under the util package

Implementation classes
The Collection implementation classes are provided by the framework libraries. And
the Java programmes, which may utilise them to create many types of collections
based on this parent and root class of the collection package. It includes some types
like ArrayList, HashMap, TreeMap, LinkedList, Doubly-LinkedList etc.

Java collection framework interface


The Collections framework has contained n number of Interfaces and their features
to define the basic nature of various collection types. Like that Collection, Set, List,
Map, Queue, Dequeue, SortedMap etc. These interfaces will use and implement with
some type of hierarchy which is provided by the collection framework. Mainly
collection is the parent root of this hierarchy if we use the List interface it maintain
the data sequence order of the elements it does not need the Uniqueness. So
uniqueness comes then it will move to the Set it will not accept the duplicates. The
Queue is the another interface that holds the user datas with a different sequence
using the Deque interface it performs the data operations. The map interface
represents the object that is referred to as both keys and values pairs for storing and
retrieving the elements.

Use of iterator
Generally, the ‘Iterator’ is one of the interfaces and it is the main part of the
collection framework for iterating the data using the loop conditions.
It is also used to navigate the collection for storing and retrieving the data element,
and delete the collection’s data elements if not required. It’s the public interface so it
calls and is imported from the util package and the programmer access its default
methods. Some of the methods like hasNext(),next(), remove() these are the three
different methods with different data types hasNext() will return only the boolean
condition, next() method returns only the object value and remove() return void this
method. It has some type like ListIterator for traverse the datas in both forward and
backward directions.

Use of comparator
The Instances of different classes can be compared using the Comparator Interface.
Generally, the class requires a natural ordering for its objects so it implements using
the Comparable Interface. If you want to design an externally configurable ordering
behaviour that overrides the default ordering behaviour, use Comparator. A
comparator interface is also used to sort the objects of a user-defined class. The
return value of the TreeSet interface which compares using the comparator set and is
used to sort the elements of the same set in a certain order is returned by this method.
If the set follows the default or natural ordering pattern, it will return a Null value.

Java collection framework architecture

4 Write short note on maps

ans The map interface is present in java.util package represents a mapping between a
key and a value. The Map interface is not a subtype of the Collection interface.
Therefore it behaves a bit differently from the rest of the collection types. A map
contains unique keys.
Maps are perfect to use for key-value association mapping such as dictionaries. The
maps are used to perform lookups by keys or when someone wants to retrieve and
update elements by keys. Some common scenarios are as follows:
● A map of error codes and their descriptions.
● A map of zip codes and cities.
● A map of managers and employees. Each manager (key) is associated
with a list of employees (value) he manages.
● A map of classes and students. Each class (key) is associated with a list of
students (value).
Since Map is an interface, objects cannot be created of the type map. We always
need a class that extends this map in order to create an object. And also, after the
introduction of Generics in Java 1.5, it is possible to restrict the type of object that
can be stored in the Map.
Map hm = new HashMap();
// Obj is the type of the object to be stored in Map
Characteristics of map interfaces
1. A Map cannot contain duplicate keys and each key can map to at most
one value. Some implementations allow null key and null values like the
HashMap and LinkedHashMap, but some do not like the TreeMap.
2. The order of a map depends on the specific implementations. For
example, TreeMap and LinkedHashMap have predictable orders, while
HashMap does not.
3. There are two interfaces for implementing Map in java. They are Map
and SortedMap, and three classes: HashMap, TreeMap, and
LinkedHashMap.
Class in map interface
1. Hashmap
HashMap is a part of Java’s collection since Java 1.2. It provides the basic
implementation of the Map interface of Java. It stores the data in (Key, Value)
pairs. To access a value one must know its key. This class uses a technique
called Hashing. Hashing is a technique of converting a large String to a small
String that represents the same String. A shorter value helps in indexing and
faster searches.
2. Linkedhashmap
LinkedHashMap is just like HashMap with an additional feature of
maintaining an order of elements inserted into it. HashMap provided the
advantage of quick insertion, search, and deletion but it never maintained the
track and order of insertion which the LinkedHashMap provides where the
elements can be accessed in their insertion order.
3. Treemap
The TreeMap in Java is used to implement the Map interface and
NavigableMap along with the Abstract Class. The map is sorted according to
the natural ordering of its keys, or by a Comparator provided at map creation
time, depending on which constructor is used. This proves to be an efficient
way of sorting and storing the key-value pairs. The storing order maintained
by the treemap must be consistent with equals just like any other sorted map,
irrespective of the explicit comparators.
Since Map is an interface, it can be used only with a class that implements this
interface. Now, let’s see how to perform a few frequently used operations on a Map
using the widely used HashMap class. And also, after the introduction of Generics in
Java 1.5, it is possible to restrict the type of object that can be stored in the map.
Operation 1: Adding Elements
In order to add an element to the map, we can use the put() method. However, the
insertion order is not retained in the hashmap. Internally, for every element, a
separate hash is generated and the elements are indexed based on this hash to make it
more efficient.
Operation 2: Changing Element
After adding the elements if we wish to change the element, it can be done by again
adding the element with the put() method. Since the elements in the map are indexed
using the keys, the value of the key can be changed by simply inserting the updated
value for the key for which we wish to change.
Operation 3: Removing Elements
In order to remove an element from the Map, we can use the remove() method. This
method takes the key value and removes the mapping for a key from this map if it is
present in the map.
Operation 4: Iterating through the Map
There are multiple ways to iterate through the Map. The most famous way is to use a
for-each loop and get the keys. The value of the key is found by using the getValue()
method.

5 Explain lambda function body with suitable program

ans Lambda expression is a new feature which is introduced in Java 8. A lambda


expression is an anonymous function. A function that doesn’t have a name and
doesn’t belong to any class. The concept of lambda expression was first introduced
in LISP programming language.

A lambda expression in Java has these main parts:


Lambda expression only has body and parameter list.
1. No name – function is anonymous so we don’t care about the name
2. Parameter list
3. Body – This is the main part of the function.
4. No return type – The java 8 compiler is able to infer the return type by checking
the code. you need not to mention it explicitly.
Lambda function interface
Lambda expression provides implementation of functional interface. An interface
which has only one abstract method is called functional interface. Java provides an
anotation @FunctionalInterface, which is used to declare an interface as functional
interface.

6 Explain lambda type interface with suitable program

ans ● Processor or SecondProcessor is called target type.


● The process of inferring the type of a lambda expression is called
● target typing.
● rules to determine whether a lambda expression is assignable to
● its target type:
● It must be a functional interface.
● The parameters of lambda expression must match the abstract method in
functional interface.
● The return type from the lambda expression is compatible with the return
type from the abstract method in functional interface.
● The checked exceptions thrown from the lambda expression must be
compatible with the declared throws clause of the abstract method in
functional interface.

7 Explain JSP architecture with suitable diagram

ans JSP architecture gives a high-level view of the working of JSP. JSP architecture is a
3 tier architecture. It has a Client, Web Server, and Database. The client is the web
browser or application on the user side. Web Server uses a JSP Engine i.e; a
container that processes JSP. For example, Apache Tomcat has a built-in JSP Engine.
JSP Engine intercepts the request for JSP and provides the runtime environment for
the understanding and processing of JSP files. It reads, parses, build Java Servlet,
Compiles and Executes Java code, and returns the HTML page to the client. The
webserver has access to the Database. The following diagram shows the architecture
of JSP.
Now let us discuss JSP which stands for Java Server Pages. It is a server-side
technology. It is used for creating web applications. It is used to create dynamic web
content. In this JSP tags are used to insert JAVA code into HTML pages. It is an
advanced version of Servlet Technology. It is a Web-based technology that helps us
to create dynamic and platform-independent web pages. In this, Java code can be
inserted in HTML/ XML pages or both. JSP is first converted into a servlet by JSP
container before processing the client’s request. JSP Processing is illustrated and
discussed in sequential steps prior to which a pictorial media is provided as a handful
pick to understand the JSP processing better which is as follows:

Step 1: The client navigates to a file ending with the .jsp extension and the browser
initiates an HTTP request to the webserver. For example, the user enters the login
details and submits the button. The browser requests a status.jsp page from the
webserver.
Step 2: If the compiled version of JSP exists in the web server, it returns the file.
Otherwise, the request is forwarded to the JSP Engine. This is done by recognizing
the URL ending with .jsp extension.
Step 3: The JSP Engine loads the JSP file and translates the JSP to Servlet(Java
code). This is done by converting all the template text into println() statements and
JSP elements to Java code. This process is called translation.
Step 4: The JSP engine compiles the Servlet to an executable .class file. It is
forwarded to the Servlet engine. This process is called compilation or request
processing phase.
Step 5: The .class file is executed by the Servlet engine which is a part of the Web
Server. The output is an HTML file. The Servlet engine passes the output as an
HTTP response to the webserver.
Step 6: The web server forwards the HTML file to the client’s browser.

8 Explain JSP session tracking types

ans Servlet are the Java programs that run on the Java-enabled web server or application
server. They are used to handle the request obtained from the webserver, process the
request, produce the response, then send a response back to the webserver
HTTP is a “stateless” protocol, which means that each time a client requests a Web
page, the client establishes a new connection with the Web server, and the server
does not retain track of prior requests.
● The conversion of a user over a period of time is referred to as a session.
In general, it refers to a certain period of time.
● The recording of the object in session is known as tracking.
● Session tracking is the process of remembering and documenting
customer conversions over time. Session management is another name for
it.
● The term “stateful web application” refers to a web application that is
capable of remembering and recording client conversions over time.

Why is Session Tracking Required?


● Because the HTTP protocol is stateless, we require Session Tracking to
make the client-server relationship stateful.
● Session tracking is important for tracking conversions in online shopping,
mailing applications, and E-Commerce applications.
● The HTTP protocol is stateless, which implies that each request is treated
as a new one.

Deleting Session Data

We have numerous alternatives once you’ve finished processing a user’s session


data.
1. Remove a specific attribute You can delete the value associated with a
specific key by calling the public void removeAttribute(String name)
function.
2. Delete your whole session. To delete an entire session, use the public void
invalidate() function.
3. Setting Session Timeout You may set the timeout for a session separately
by calling the public void setMaxInactiveInterval(int interval) function.
4. Log the user out On servers that support servlets 2.4, you may use the
logout method to log the client out of the Web server and invalidate all of
the users’ sessions.
5. web.xml Configuration If you’re using Tomcat, you may set the session
timeout in the web.xml file, in addition to the ways listed above.

<session-config>
<session-timeout>20</session-timeout>
</session-config>
The timeout is specified in minutes and overrides Tomcat’s default timeout of 30
minutes.
In a servlet, the getMaxInactiveInterval() function delivers the session’s timeout
period in seconds. GetMaxInactiveInterval() returns 900 if your session is set to 20
minutes in web.xml.

ession Tracking employs Four Different techniques

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

A. Cookies
Cookies are little pieces of data delivered by the web server in the response header
and kept by the browser. Each web client can be assigned a unique session ID by a
web server. Cookies are used to keep the session going. Cookies can be turned off by
the client.
B. Hidden Form Field
The information is inserted into the web pages via the hidden form field, which is
then transferred to the server. These fields are hidden from the user’s view.
C. URL Rewriting
With each request and return, append some more data via URL as request
parameters. URL rewriting is a better technique to keep session management and
browser operations in sync.
D. HttpSession
A user session is represented by the HttpSession object. A session is established
between an HTTP client and an HTTP server using the HttpSession interface. A user
session is a collection of data about a user that spans many HTTP requests.

9 Explain JSP bean

ans A JavaBean is a specially constructed Java class written in the Java and coded
according to the JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java
classes −
● It provides a default, no-argument constructor.
● It should be serializable and that which can implement the Serializable
interface.
● It may have a number of properties which can be read or written.
● It may have a number of "getter" and "setter" methods for the
properties.

JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user of the
object. The attribute can be of any Java data type, including the classes that you
define.
A JavaBean property may be read, write, read only, or write only. JavaBean
properties are accessed through two methods in the JavaBean's implementation class

1. getPropertyName()
For example, if property name is firstName, your method name would be
getFirstName() to read that property. This method is called accessor.
2. setPropertyName()
For example, if property name is firstName, your method name would be
setFirstName() to write that property. This method is called mutator.
A read-only attribute will have only a getPropertyName() method, and a write-only
attribute will have only a setPropertyName() method.

Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean
becomes a scripting variable that can be accessed by both scripting elements and
other custom tags used in the JSP. The full syntax for the useBean tag is as follows −
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application
based on your requirement. The value of the id attribute may be any value as a long
as it is a unique name among other useBean declarations in the same JSP.

Accessing JavaBeans Properties


Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to
access the get methods and the <jsp:setProperty/> action to access the set methods.
Here is the full syntax −
<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">
<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
...........
</jsp:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP
by the useBean action. The property attribute is the name of the get or the set
methods that should be invoked.

10 Write short note on auto writing bean lookup

ans
Autowiring feature of spring framework enables you to inject the object dependency
implicitly. It internally uses setter or constructor injection.

Autowiring can't be used to inject primitive and string values. It works with
reference only.

Advantage of Autowiring

It requires the less code because we don't need to write the code to inject the
dependency explicitly.

Disadvantage of Autowiring

No control of programmer.

It can't be used for primitive and string values.

byName autowiring mode

In case of byName autowiring mode, bean id and reference name must be same.

It internally uses setter injection.

<bean id="b" class="org.sssit.B"></bean>


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

byType autowiring mode

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

<bean id="b1" class="org.sssit.B"></bean>


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

constructor autowiring mode

In case of constructor autowiring mode, spring container injects the dependency by


highest parameterized constructor.

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

<bean id="b" class="org.sssit.B"></bean>


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

no autowiring mode

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


autowiring.

<bean id="b" class="org.sssit.B"></bean>


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

11 Write short note on spring framework

ans The Spring Framework is an open-source framework for building enterprise Java
applications. Spring aims to simplify the complex and cumbersome enterprise Java
application development process by offering a framework that includes technologies
such as:
1. Aspect-oriented programming (AOP)
2. Dependency injection (DI)
3. Plain Old Java Object (POJO)
Even with all these technologies, Spring is a lightweight framework that can be used
to create scalable, secure, and robust enterprise web applications.

At a macro-level, we can consider the Spring framework a collection of sub


frameworks such as Spring Web Flow, Spring MVC, and Spring ORM. In addition to
Java, Spring also supports Kotlin and Groovy.
The above diagram represents the basic components of the Spring architecture. As
you can see, Spring is built using different modules that enable different
functionality.
Core container
This contains the fundamental modules that are the cornerstone of the Spring
framework.

● Core (spring-core) is the core of the framework that power features such as
Inversion of Control and dependency injection.
● Beans (spring-beans) provides Beanfactory, which is a sophisticated
implementation of the factory pattern.
● Context (spring-context) builds on Core and Beans and provides a medium
to access defined objects. ApplicationContext interface is the core part of the
Context module, and the spring-context-support provides support for
third-party interactions such as caching, mailing, and template engines.
● SpEL (spring-expression) enables users to use the Spring Expression
Language to query and manipulate the object graph at runtime.

Data access/integration
This includes the modules that are used to handle data access and transaction
processing in an application.

● JDBC (spring-jdbc) provides a JDBC abstraction layer that eliminates the


need to separate JDBC coding when dealing with databases.
● ORM (spring-orm) are integration layers for popular object-relational
mapping API such as JPA, JDO Hibernate.
● OXM (spring-oxm) is the abstraction layer that supports Object/XML
mapping implementations like JAXB, XStream.
● JMS (spring-jms) is the Java Messaging Service module that creates and
consumes messages that directly integrate with the Spring messaging module.
● Transaction (spring-tx) offers programmatic and declarative transaction
management for classes that include special interfaces and POJOs.

Web
The Web layer relates to modules that power web-based functions in Spring.

● WebSocket (spring-websocket) powers the web socket-based


communication for clients and servers.
● Servlet (spring-webmvc) is the Spring WebMVC module that contains the
MVC and REST implementations.
● Web (spring-web) provides all the basic web-oriented features and contains
an HTTP client and web-related parts of the Spring remoting.
● Portlet (spring-webmvc-portlet) provides the MVC implementation to be
used in a portlet environment.

Other Modules
● AOP (spring-aop) provides an aspect-oriented programming implementation
that can be used when creating applications.
● Aspects (spring-aspects) enables direct integration with the AspectJ
programming extension by the eclipse foundation.
● Instrumentation (spring-instrument) is the class instrumentation support
and class loader implementations for application servers.
● Messaging (spring-messaging) provides a robust platform to manage
messaging in applications.
● Test (spring-test) is the Spring test module that supports unit and integration
testing with JUnit and TestNG.

12 Write short note on dependency injection

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

Problems of Dependency Lookup

There are mainly two problems of dependency lookup.

● 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.
● 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

Spring framework provides two ways to inject dependency

● By Constructor
● By Setter method

Dependency Injection by Constructor

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.

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.

13 Write short note on Spring manage beans

ans The objects that form the backbone of your application and that are managed by the
Spring IoC container are called beans. A bean is an object that is instantiated,
assembled, and otherwise managed by a Spring IoC container. These beans are
created with the configuration metadata that you supply to the container. For
example, in the form of XML <bean/> definitions which you have already seen in
the previous chapters.
Bean definition contains the information called configuration metadata, which is
needed for the container to know the following −
● How to create a bean
● Bean's lifecycle details
● Bean's dependencies

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 the bean.
2. Name - This attribute specifies the bean identifier uniquely. In XMLbased
configuration metadata, you use the id and/or name attributes to specify the
bean identifier(s).
3. Scope - This attribute specifies the scope of the objects created from a
particular bean definition and it will be discussed in bean scopes chapter.
4. scope
This attribute specifies the scope of the objects created from a particular bean
definition and it will be discussed in bean scopes chapter.
5. properties
This is used to inject the dependencies and will be discussed in subsequent
chapters.
6. autowiring mode
This is used to inject the dependencies and will be discussed in subsequent
chapters.
7. lazy-initialization mode
A lazy-initialized bean tells the IoC container to create a bean instance when
it is first requested, rather than at the startup.
8. initialization method
A callback to be called just after all necessary properties on the bean have
been set by the container. It 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
will be discussed in bean life cycle chapter.

Spring Configuration Metadata


Spring IoC container is totally decoupled from the format in which this configuration
metadata is actually written. Following are the three important methods to provide
configuration metadata to the Spring Container −
● XML based configuration file.
● Annotation-based configuration
● Java-based configuration

14 With a suitable program explain dependency injection with spring- setter injection

ans 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

Let's see the simple example to inject primitive and string-based values by setter
method. We have created three files here:

● Employee.java
● applicationContext.xml
● Test.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 com.javatpoint;
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;
}
public String getCity() {
return city;
}
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="com.javatpoint.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.

package com.javatpoint;

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

}
}

Output:20 Arun ghaziabad

15 Write short note on AOP

ans 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.
Spring AOP module provides interceptors to intercept an application. For example,
when a method is executed, you can add extra functionality before or after the
method execution.

AOP Terminologies
Before we start working with AOP, let us become familiar with the AOP concepts
and terminology. These terms are not specific to Spring, rather they are related to
AOP.
1. Aspect
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.
2. Join point
This represents a point in your application where you can plug-in the AOP
aspect. You can also say, it is the actual place in the application where an
action will be taken using Spring AOP framework.
3. Advice
This is the actual action to be taken either before or after the method
execution. This is an actual piece of code that is invoked during the program
execution by Spring AOP framework.
4. Pointcut
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.
5. Introduction
An introduction allows you to add new methods or attributes to the existing
classes.
6. Target object
The object being advised by one or more aspects. This object will always be a
proxied object, also referred to as the advised object.
7. 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.
Types of Advice
Spring aspects can work with five kinds of advice mentioned as follows −
1. before
Run advice before the a method execution.
2. after
Run advice after the method execution, regardless of its outcome.
3. after-returning
Run advice after the a method execution only if method completes
successfully.
4. after-throwing
Run advice after the a method execution only if method exits by throwing an
exception.
5. around
Run advice before and after the advised method is invoked.

Custom Aspects Implementation


Spring supports the @AspectJ annotation style approach and the schema-based
approach to implement custom aspects. These two approaches have been explained
in detail in the following sections.
1. XML Schema based
Aspects are implemented using the regular classes along with XML based
configuration.
2. @AspectJ based
@AspectJ refers to a style of declaring aspects as regular Java classes
annotated with Java 5 annotations.

16 Write short note on Types of advice

ans
AOP

AOP (Aspect-Oriented Programming) is a programming pattern that increases


modularity by allowing the separation of the cross-cutting concern. These
cross-cutting concerns are different from the main business logic. We can add
additional behavior to existing code without modification of the code itself.

Spring's AOP framework helps us to implement these cross-cutting concerns.

Using AOP, we define common functionality in one place. We are free to define how
and where this functionality is applied without modifying the class to which we are
applying the new feature. The cross-cutting concern can now be modularized into
special classes, called aspect.

Types of AOP Advices

There are five types of AOP advices are as follows:

● Before Advice
● After Advice
● Around Advice
● After Throwing
● After Returning

Before Advice: An advice that executes before a join point, is called before advice.
We use @Before annotation to mark an advice as Before advice.

After Advice: An advice that executes after a join point, is called after advice. We
use @After annotation to mark an advice as After advice.

Around Advice: An advice that executes before and after of a join point, is called
around advice.

After Throwing Advice: An advice that executes when a join point throws an
exception.

After Returning Advice: An advice that executes when a method executes


successfully.

17 Write short note on Joinpoint

ans A Joinpoint is a point in Spring AOP during the execution of a program, such as the
execution of a method or the handling of an exception, etc. This symbolizes a point
in your web application where you can easily plug in the AOP aspect of your
software. In Spring AOP, a JoinPoint always represents a method execution. It is
mainly the actual place in the web application where an action will be executed using
the Spring AOP framework.

18 Explain pointcut designators.

ans In this article, you will learn about the Pointcut expressions used to match advice
with the target Joinpoints. Spring AOP uses AspectJ pointcut expressions. In the
tutorial home page, you read the Pointcut definition. Spring AOP only supports
method execution join points, so you can think of a pointcut as matching the
execution of methods on Spring beans.
In simple words, a pointcut expression is like a Regular Expression which
determines the classes and methods where the Advice will be executed.

Declaring a Pointcut
Declaring a pointcut is simple, all you need is annotate the method with
@Pointcut(POINTCUT_EXPRESSION).

1. @Pointcut("execution(* transfer(..))") // the pointcut expression


2. private void anyTransfer() {} //pointcut signature

It is optional to use @Pointcut instead, the pointcut expressions can be directly used
inside the advice annotations as shown below.

● Before advice –@Before


● Around advice – @Around
● After returning – @AfterReturning
● After throwing – @AfterThrowing
● After (finally) advice – @After
● @Before("execution(* c.jbd.saop.gettingstarted.dao.*.add(..))")
● public void allRepoAddMethods(JoinPoint joinPoint) {
● //Aspect body
● }

The term execution inside the @Before or @Pointcut annotation is known as


Pointcut designators. Spring provides several designators which are discussed next.

Supported Pointcut Designators


Spring AOP supports the following Pointcut Designators (PCD).

● execution – for matching method execution join points. This is the most
widely used PCD.
● within – for matching methods of classes within certain types e.g. classes
within a package.
● @within – for matching to join points within types (target object class) that
have the given annotation.
● this – for matching to join points (the execution of methods) where the bean
reference (Spring AOP proxy) is an instance of the given type.
● target – for matching with the target object of the specific instance type.
● @target – for matching with the target object annotated with a specific
annotation.
● args – for matching with methods where its arguments are of a specific type.
● @args – for matching with methods where its arguments are annotated with a
specific annotation.
● @annotation – for matching to join points where the subject (method) of the
Joinpoint has the given annotation.
● bean (idOrNameOfBean) – This PCD lets you limit the matching of join
points to a particular named Spring bean or to a set of named Spring beans
(when using wildcards).

AspectJ provides several other designators which are not supported in Spring AOP,
only the above mentioned PCD are supported.

Combining Pointcut Expressions


You can combine multiple pointcut expressions by using AND – &&, OR – || and
NOT – !. You can also refer to pointcut expressions by name.

Various Pointcut designators example

1. execution designator
This is the most widely used designator that everyone needs to know, used to match
the method execution Joinpoint. The syntax of an execution() designator is discussed
below.

execution(modifiers-pattern? return-type-pattern declaring-type-pattern?


name-pattern( param-pattern)
throws-pattern?)

2. within and @within designators


The within is used for matching methods of classes within certain types e.g. classes
within a package.

Similarly, the @within is used for matching with join points (method execution)
where the declared class of the target object has a given annotation.

3. The this designator


It limits the matching to join points (the execution of methods) where the bean
reference (Spring AOP proxy) is an instance of the given type.
For example, match with any join point (method execution) where the proxy
implements the AccountService interface.

"this(com.jbd.service.AccountService)"

4. The target and @target designators


The target designator limits matching to join points (the execution of methods)
where the target object (application object being proxied) is an instance of the given
type. e.g. when the target object implements a specific interface.

Example, any join point where the target object implements the AccountService
interface.

"target(com.jbd.service.AccountService)"

5. The args and @args designators


The args limits matching to join points (the execution of methods) where the
arguments are instances of a given types.

For example, any join point (method execution) that takes a single parameter and
where the argument passed at runtime is Serializable.

"args(java.io.Serializable)"

6. The @annotation designator


The @annotation designator limits matching to join points where the subject of the
join point (the method being executed) has the given annotation.

Example, match with any join point (method execution) where the executing method
has an @Transactional annotation.

"@annotation(org.springframework.transaction.annotation.Transactional)"

7. The bean Pointcut designator


The bean PCD lets you limit the matching of join points to a particular named Spring
bean or to a set of named Spring beans (when using wildcards).

Example, any join point (method execution) on Spring beans having names that
match the wildcard expression *Manager.

"bean(*Manager)"

19 Write short note on Spring JDBC Data Access


ans While working with the database using plain old JDBC, it becomes cumbersome to
write unnecessary code to handle exceptions, opening and closing database
connections, etc. However, Spring JDBC Framework takes care of all the low-level
details starting from opening the connection, prepare and execute the SQL statement,
process exceptions, handle transactions and finally close the connection.

So what you have to do is just define the connection parameters and specify the SQL
statement to be executed and do the required work for each iteration while fetching
data from the database.

Spring JDBC provides several approaches and correspondingly different classes to


interface with the database. I'm going to take classic and the most popular approach
which makes use of JdbcTemplate class of the framework. This is the central
framework class that manages all the database communication and exception
handling.

Configuring Data Source


Let us create a database table Student in our database TEST. We assume you are
working with MySQL database, if you work with any other database then you can
change your DDL and SQL queries accordingly.

CREATE TABLE Student(


ID INT NOT NULL AUTO_INCREMENT ,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);
Now we need to supply a DataSource to the JDBC Template so it can configure itself
to get database access. You can configure the DataSource in the XML file with a
piece of code as shown in the following code snippet −

<bean id = "dataSource"
class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
<property name = "username" value = "root"/>
<property name = "password" value = "password"/>
</bean>
Data Access Object (DAO)
DAO stands for Data Access Object, which is commonly used for database
interaction. DAOs exist to provide a means to read and write data to the database and
they should expose this functionality through an interface by which the rest of the
application will access them.

The DAO support in Spring makes it easy to work with data access technologies like
JDBC, Hibernate, JPA, or JDO in a consistent way.

20 Write short note on JdbcTemplate

ans
Spring JdbcTemplate is a powerful mechanism to connect to the database and
execute SQL queries. It internally uses JDBC api, but eliminates a lot of problems of
JDBC API.

Problems of JDBC API

The problems of JDBC API are as follows:

● We need to write a lot of code before and after executing the query, such as
creating connection, statement, closing resultset, connection etc.
● We need to perform exception handling code on the database logic.
● We need to handle transaction.
● Repetition of all these codes from one to another database logic is a time
consuming task.

Advantage of Spring JdbcTemplate

Spring JdbcTemplate eliminates all the above mentioned problems of JDBC API. It
provides you methods to write the queries directly, so it saves a lot of work and time.

Spring Jdbc Approaches

Spring framework provides following approaches for JDBC database access:

● JdbcTemplate
● NamedParameterJdbcTemplate
● SimpleJdbcTemplate
● SimpleJdbcInsert and SimpleJdbcCall
JdbcTemplate class

It is the central class in the Spring JDBC support classes. It takes care of creation and
release of resources such as creating and closing of connection object etc. So it will
not lead to any problem if you forget to close the connection.

It handles the exception and provides the informative exception messages by the help
of excepion classes defined in the org.springframework.dao package.

We can perform all the database operations by the help of JdbcTemplate class such as
insertion, updation, deletion and retrieval of the data from the database.
21 Write short note on approaches for JDBC database access

ans In addition to three flavors of the JdbcTemplate, a new SimpleJdbcInsert and


SimplejdbcCall approach optimizes database metadata, and the RDBMS Object style
takes a more object-oriented approach similar to that of JDO Query design.

Once you start using one of these approaches, you can still mix and match to include
a feature from a different approach. All approaches require a JDBC 2.0-compliant
driver, and some advanced features require a JDBC 3.0 driver.

JDBC database access - approach


● JdbcTemplate is the classic Spring JDBC approach and the most popular.
This "lowest level" approach and all others use a JdbcTemplate under the
covers, and all are updated with Java 5 support such as generics and varargs.
● NamedParameterJdbcTemplate wraps a JdbcTemplate to provide named
parameters instead of the traditional JDBC "?" placeholders. This approach
provides better documentation and ease of use when you have multiple
parameters for an SQL statement.
● SimpleJdbcTemplate combines the most frequently used operations of
JdbcTemplate and NamedParameterJdbcTemplate.
● SimpleJdbcInsert and SimpleJdbcCall optimize database metadata to limit
the amount of necessary configuration. This approach simplifies coding so
that you only need to provide the name of the table or procedure and provide
a map of parameters matching the column names. This only works if the
database provides adequate metadata. If the database doesn't provide this
metadata, you will have to provide explicit configuration of the parameters.
● RDBMS Objects including MappingSqlQuery, SqlUpdate and
StoredProcedure requires you to create reusable and thread-safe objects
during initialization of your data access layer. This approach is modeled after
JDO Query wherein you define your query string, declare parameters, and
compile the query. Once you do that, execute methods can be called multiple
times with various parameter values passed in.

22 Write short note on NamedParameterJdbcTemplate

ans The org.springframework.jdbc.core.NamedParameterJdbcTemplate class is a


template class with a basic set of JDBC operations, allowing the use of named
parameters rather than traditional '?' placeholders. This class delegates to a wrapped
JdbcTemplate once the substitution from named parameters to JDBC style '?'
placeholders is done at execution time. It also allows to expand a list of values to the
appropriate number of placeholders.

Interface Declaration
Following is the declaration for
org.springframework.jdbc.core.NamedParameterJdbcTemplate class −

public class NamedParameterJdbcTemplate


extends Object
implements NamedParameterJdbcOperations

Syntax
MapSqlParameterSource in = new MapSqlParameterSource();
in.addValue("id", id);
in.addValue("description", new SqlLobValue(description, new
DefaultLobHandler()), Types.CLOB);
String SQL = "update Student set description = :description where id = :id";
NamedParameterJdbcTemplate jdbcTemplateObject = new
NamedParameterJdbcTemplate(dataSource);
jdbcTemplateObject.update(SQL, in);
Where,

● in − SqlParameterSource object to pass a parameter to update a query.


● SqlLobValue − Object to represent an SQL BLOB/CLOB value
parameter.
● jdbcTemplateObject − NamedParameterJdbcTemplate object to update
student object in the database.

To understand the above-mentioned concepts related to Spring JDBC, let us write an


example which will update a query. To write our example, let us have a working
Eclipse IDE in place and use the following steps to create a Spring application.

● Update the project Student created under chapter Spring JDBC - First
Application
● Update the bean configuration and run the application as explained below.

23 Write short note on SimpleJdbcTemplate

ans The SimpleJDBCTemplate includes all the features and functionalities of


JdbcTemplate class and it also supports the Java5 features such as
var-args(variable arguments) and autoboxing. Along with JdbcTemplate class, it also
provides the update() method which takes two arguments the SQL query and
arbitrary arguments which depend upon the SQL query. In order to access the
methods of the old JdbcTemplate class, we use the getJdbcOperations() method and
we call all those methods over SimpleJdbcTemplate.
Syntax for update() method of SimpleJDBCTemplate class:
int update(String sqlQuery, Object parameters)
Step By Step Implementation
Step 1: Create Table
In this step, we will create a Student table to store students’ information. For this
tutorial, we will assume you have created the following table in your database.
Step 2: Adding dependencies
In this step, we will add the maven dependencies to our application. Add the
following dependencies to your pom.xml
Step 3: Create a model class
Now, we will create a model class for our students. This class will have
three-member variables id, name, and department. We will also define its
constructors, getters and setters methods, and toString() method.
Step 4: Create a DAO class
In this step, we will create a StudentDao.java class. In this class, we will define
SimpleJdbcTemplate and update() method and provide its definition to update our
data.
Step 5: Bean Configuration
In this step, we will create the spring configuration file and name it
application-context.xml. In order to make a connection to the database, we need the
following information username, password, database connection, URL, and the
driver class name. All this information is contained in the
DriverManagerDataSource class, it has the getConnection() method which returns
a connection of java type. We are using the instance of SimpleJdbcTemplate in our
StudentDao class and passing it using the constructor injection method.
Step 6: Creating Utilities Class
Now, we will create a Utility class for testing our application. For this create a new
class and name it TestSimpleJDBCTemplate.java and add the following code to it.

You might also like