Assignment
Unit-1: Overview of Spring and The IoC Container
1. Long Answer Questions (Descriptive)
1. Explain
the architecture of the Spring Framework. Discuss its
different modules and their purposes.
2. Define
the IoC (Inversion of Control) Container. Explain how it works
with an example.
3. What
are Spring Beans? How are they defined, configured, and
managed in the IoC container?
4. Discuss
Dependency Injection (DI) in detail. Differentiate between Constructor
Injection and Setter Injection with examples.
5. Explain
the different bean scopes supported by Spring. Give suitable
use cases for each.
6. Compare
Spring Framework with other frameworks such as Struts and
Hibernate.
7. Why
is Spring considered lightweight? Illustrate with an example.
8. Describe
the lifecycle of a Spring Bean with neat explanation.
9. How
does Spring achieve loose coupling in applications? Give
examples.
10. Write a
detailed note on advantages of using Spring IoC container in
enterprise applications.
2. Short Answer Questions
1. Define
the term Spring Framework.
2. What
do you mean by Inversion of Control?
3. List
any three features of Spring Framework.
4. What
is a BeanFactory?
5. Differentiate
between BeanFactory and ApplicationContext.
6. What
is autowiring in Spring?
7. Define
Singleton and Prototype bean scopes.
8. State
one example of setter injection.
9. What
is the default scope of a Spring bean?
10. Write one
difference between tight coupling and loose coupling.
3. Multiple Choice Questions (MCQs)
1. Which
of the following is the core feature of Spring?
a) Database handling
b) Dependency Injection
c) GUI design
d) File management
Answer: b) Dependency Injection
2. The
IoC Container in Spring is responsible for:
a) Managing database connections
b) Creating and managing beans
c) Handling JSP pages
d) Generating SQL queries
Answer: b) Creating and managing beans
3. Which
interface is the basic container in Spring?
a) ApplicationContext
b) BeanFactory
c) ServletContext
d) ConfigurableListableBeanFactory
Answer: b) BeanFactory
4. The
default scope of a Spring bean is:
a) Prototype
b) Session
c) Singleton
d) Request
Answer: c) Singleton
5. Which
of the following is NOT a valid dependency injection method in Spring?
a) Constructor Injection
b) Interface Injection
c) Setter Injection
d) Field Injection (via annotations)
Answer: b) Interface Injection
6. ApplicationContext
is a superset of:
a) BeanFactory
b) ServletContext
c) DispatcherServlet
d) Hibernate SessionFactory
Answer: a) BeanFactory
7. Which
XML tag is used to define beans in Spring configuration file?
a) <object>
b) <bean>
c) <class>
d) <context>
Answer: b) <bean>
8. In
Spring, @Autowired
annotation is
used for:
a) Logging
b) Database connectivity
c) Dependency Injection
d) Bean Scoping
Answer: c) Dependency Injection
4. Fill in the Blanks
1. The
_______ design principle is implemented by Spring to achieve
loose coupling.
Answer: Inversion of Control (IoC)
2. The
central interface of Spring IoC container is _______.
Answer: BeanFactory
3. By
default, Spring beans are of scope _______.
Answer: Singleton
4. The
two main types of dependency injection are _______ and _______.
Answer: Constructor Injection, Setter Injection
5. The
_______ interface is an advanced version of BeanFactory.
Answer: ApplicationContext
6. In
Spring configuration file, beans are defined using _______
tag.
Answer: <bean>
7. _______
scope creates a new bean instance for each HTTP request.
Answer: Request
8. Spring
Framework is written in _______ programming language.
Answer: Java
9. The
annotation _______ is used for automatic dependency injection.
Answer: @Autowired
10. A Spring
bean is simply a _______ managed by IoC container.
Answer: Java Object
5. Programming Questions
Q1. Write a simple Spring application to
demonstrate IoC
Container and Bean creation using XML configuration.
<!-- beans.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.example.Student">
<property name="name" value="John Doe"/>
<property name="rollNo" value="101"/>
</bean>
</beans>
// Student.java
package com.example;
public class Student {
private String name;
private int rollNo;
public void setName(String name) { this.name = name; }
public void setRollNo(int rollNo) { this.rollNo = rollNo; }
public void display() {
System.out.println("Student Name: " + name);
System.out.println("Roll No: " + rollNo);
}
}
// MainApp.java
package com.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
student.display();
}
}
Q2. Write a program to demonstrate Constructor Injection in Spring.
<!-- beans.xml -->
<bean id="car" class="com.example.Car">
<constructor-arg value="Tesla"/>
<constructor-arg value="2025"/>
</bean>
// Car.java
package com.example;
public class Car {
private String model;
private int year;
public Car(String model, int year) {
this.model = model;
this.year = year;
}
public void showDetails() {
System.out.println("Car Model: " + model + " | Year: " + year);
}
}
// MainApp.java
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Car car = (Car) context.getBean("car");
car.showDetails();
Q3. Demonstrate Bean Scopes in Spring (Singleton vs Prototype).
<!-- beans.xml -->
<bean id="myBean" class="com.example.MyBean" scope="prototype"/>
// MyBean.java
package com.example;
public class MyBean {
public MyBean() {
System.out.println("MyBean instance created!");
}
}
// MainApp.java
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
MyBean obj1 = (MyBean) context.getBean("myBean");
MyBean obj2 = (MyBean) context.getBean("myBean");
System.out.println(obj1 == obj2); // false for prototype, true for singleton
✅ This assignment covers:
·
Introduction to Spring
·
IoC Container and Beans
·
Dependencies & Dependency Injection
·
Bean Scopes
·
Theory + Practice
Unit-2: Resources and Validation
1. Long Answer Questions (Descriptive)
1. Explain
the Resource Interface in Spring. Why is it important? Provide
examples.
2. What
are the different types of built-in resources supported by
Spring? Explain each with examples.
3. Describe
the ResourceLoader interface in Spring. How does it help in
accessing resources?
4. Discuss
the role of the Spring Validator interface. Write an example
for validating user input.
5. What
is the difference between programmatic validation and declarative
validation in Spring?
6. Explain
the use of Spring’s type conversion system. How does it differ
from Java’s default type conversion?
7. How
can you load resources from different sources (file system, classpath, URL)
using Spring? Provide examples.
8. Write
a note on the importance of validation in enterprise
applications.
9. Discuss
the integration of Spring Validator with Spring MVC.
10. Illustrate
with examples how Spring’s conversion service is used to
convert custom data types.
2. Short Answer Questions
1. What
is the Resource Interface?
2. Mention
two examples of built-in resources in Spring.
3. What
is the function of a ResourceLoader?
4. Which
method in the Validator interface is used to check if a class
can be validated?
5. Write
the method signature of the validate()
method in the Validator interface.
6. State
one difference between PropertyEditor and ConversionService.
7. What
is type safety in the context of Spring’s type conversion?
8. Which
interface is used for validation in Spring?
9. What
does ClassPathResource
do?
10. Which
method of ResourceLoader loads resources?
3. Multiple Choice Questions (MCQs)
1. The
Resource interface in Spring is defined in:
a) org.springframework.beans
b) org.springframework.core.io
c) org.springframework.context
d) org.springframework.resource
Answer: b) org.springframework.core.io
2. Which
of the following is NOT a built-in resource type in Spring?
a) ClassPathResource
b) FileSystemResource
c) ServletContextResource
d) JSONResource
Answer: d) JSONResource
3. The
main method of ResourceLoader is:
a) loadResource()
b) getResource()
c) fetchResource()
d) resolveResource()
Answer: b) getResource()
4. The
Validator interface in Spring belongs to:
a) org.springframework.context
b) org.springframework.validation
c) org.springframework.core
d) org.springframework.web
Answer: b) org.springframework.validation
5. Which
two methods are defined in Spring’s Validator interface?
a) supports()
, validate()
b) check()
, validate()
c) init()
, supports()
d) verify()
, validate()
Answer: a) supports(), validate()
6. Which
class provides type conversion in Spring?
a) PropertyEditor
b) ConversionService
c) ResourceLoader
d) ValidatorAdapter
Answer: b) ConversionService
7. Spring’s
type conversion system is based on:
a) java.beans
b) org.springframework.core.convert
c) org.springframework.validation
d) org.springframework.resources
Answer: b) org.springframework.core.convert
8. FileSystemResource
is used to:
a) Load resources from URL
b) Load resources from file system path
c) Load resources from classpath
d) Load resources from servlet context
Answer: b) Load resources from file system path
4. Fill in the Blanks
1. The
_______ interface represents an external resource in Spring.
Answer: Resource
2. _______
is used to load resources in Spring.
Answer: ResourceLoader
3. _______
resource loads files from the application’s classpath.
Answer: ClassPathResource
4. The
Validator interface has two methods: _______
and _______.
Answer: supports(), validate()
5. _______
is the default type conversion system in Spring.
Answer: ConversionService
6. _______
resource is used to access files within a web application context.
Answer: ServletContextResource
7. The
validate()
method in
Spring’s Validator interface accepts two arguments: _______
and _______.
Answer: Object target, Errors errors
8. Spring’s
type conversion is more flexible than Java’s _______.
Answer: PropertyEditor
9. The
getResource()
method of _______
interface is used to fetch resources.
Answer: ResourceLoader
10. Spring
validation helps ensure _______ and _______
of application data.
Answer: correctness, consistency
5. Programming Questions
Q1. Demonstrate loading a resource from classpath using ClassPathResource
.
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import java.io.InputStream;
public class ResourceDemo {
public static void main(String[] args) throws Exception {
Resource resource = new ClassPathResource("data.txt");
InputStream inputStream = resource.getInputStream();
byte[] data = new byte[inputStream.available()];
inputStream.read(data);
System.out.println(new String(data));
}
}
Q2. Demonstrate the use of ResourceLoader.
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
public class ResourceLoaderDemo {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Resource resource = context.getResource("classpath:data.txt");
System.out.println("Resource File Name: " + resource.getFilename());
}
}
Q3. Write a program to demonstrate Spring Validator.
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
class Student {
private String name;
private int age;
// getters and setters
}
class StudentValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Student.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Student student = (Student) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.empty", "Name is required");
if(student.getAge() < 18) {
errors.rejectValue("age", "age.invalid", "Age must be at least 18");
}
}
}
Q4. Demonstrate Spring Type Conversion using ConversionService.
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
public class ConversionDemo {
public static void main(String[] args) {
ConversionService conversionService = new DefaultConversionService();
String number = "100";
Integer value = conversionService.convert(number, Integer.class);
System.out.println("Converted Value: " + value);
}
}
✅ This covers:
·
Resource Interface
·
Built-in Resources
·
Resource Loader
·
Validation using Spring Validator
·
Spring Type Conversion
Unit-3: Spring Expression Language (SpEL)
1. Long Answer Questions (Descriptive)
1. Explain
the Spring Expression Language (SpEL). What are its features
and use cases?
2. Describe
the evaluation process of SpEL with suitable examples.
3. How
are SpEL expressions used in bean definitions? Write an
example.
4. Discuss
the role of literal expressions in SpEL with examples.
5. How
can SpEL be used to access properties of a bean? Illustrate
with code.
6. Explain
how arrays, lists, and maps can be accessed and manipulated
using SpEL.
7. Differentiate
between inline lists and inline maps in SpEL
with examples.
8. Describe
indexer expressions in SpEL. Show how they are used to access
elements in collections.
9. Discuss
the advantages of using SpEL over standard Java expressions in
Spring applications.
10. Write a
note on real-time scenarios where SpEL is extensively used in
enterprise applications.
2. Short Answer Questions
1. What
is SpEL?
2. Mention
one use of SpEL in Spring.
3. What
does the #{}
operator signify in
SpEL?
4. Write
an example of a literal expression in SpEL.
5. How
do you access the length of a string in SpEL?
6. What
is an indexer in SpEL?
7. Write
one difference between inline lists and Java lists.
8. Which
symbol is used to define inline maps in SpEL?
9. What
does T(java.lang.Math).PI
return
in SpEL?
10. Can SpEL be
used in Spring annotations? (Yes/No)
3. Multiple Choice Questions (MCQs)
1. SpEL
is supported in Spring since version:
a) 2.0
b) 3.0
c) 4.0
d) 5.0
Answer: b) 3.0
2. The
syntax used for SpEL expressions in XML is:
a) ${}
b) #{}
c) @{}
d) &{}
Answer: b) #{}`
3. Which
of the following is a literal expression?
a) #{5+10}
b) #{'Hello'}
c) #{bean.name}
d) #{list[0]}
Answer: b) #{'Hello'}`
4. Inline
lists in SpEL are created using:
a) [ ]
b) { }
c) ( )
d) < >
Answer: a) [ ]
5. Inline
maps in SpEL are created using:
a) [key:value]
b) {key:value}
c) <key,value>
d) (key:value)
Answer: b) {key:value}
6. Which
SpEL operator is used to access bean properties?
a) .
(dot)
b) :
c) ->
d) =>
Answer: a) . (dot)
7. SpEL
indexers can be applied to:
a) Arrays
b) Lists
c) Maps
d) All of the above
Answer: d) All of the above
8. To
call static methods in SpEL, we use:
a) S(ClassName).method()
b) T(ClassName).method()
c) C(ClassName).method()
d) M(ClassName).method()
Answer: b) T(ClassName).method()
4. Fill in the Blanks
1. SpEL
expressions in Spring are defined using _______ syntax.
Answer: #{ }
2. A
string literal in SpEL is enclosed within _______.
Answer: single quotes (‘ ’)
3. Inline
lists in SpEL are declared using _______ brackets.
Answer: square [ ]
4. Inline
maps in SpEL are declared using _______ brackets.
Answer: curly { }
5. To
call a static field or method in SpEL, the syntax used is T(className).field/method.
6. In
SpEL, _______ is used to access a property of a bean.
Answer: dot (.) operator
7. _______
are used to access elements of arrays, lists, or maps in SpEL.
Answer: Indexers ( [ ] )
8. The
SpEL engine evaluates expressions at _______ (compile time /
runtime).
Answer: runtime
9. The
T(java.lang.Math).sqrt(25)
returns _______.
Answer: 5.0
10. SpEL can be
used in both _______ and _______
configurations in Spring.
Answer: XML, Annotation-based
5. Programming Questions
Q1. Demonstrate a simple SpEL literal expression in XML configuration.
<bean id="myBean" class="com.example.MyBean">
<property name="message" value="#{'Hello SpEL!'}"/>
<property name="number" value="#{10+20}"/>
</bean>
public class MyBean {
private String message;
private int number;
// setters and getters
}
Q2. Access bean properties using SpEL.
<bean id="student" class="com.example.Student">
<property name="name" value="John"/>
<property name="age" value="22"/>
</bean>
<bean id="school" class="com.example.School">
<property name="studentName" value="#{student.name}"/>
</bean>
Q3. Using arrays, lists, and indexers in SpEL.
<bean id="dataBean" class="com.example.DataBean">
<property name="numbers" value="#{{1,2,3,4}}"/>
<property name="firstNumber" value="#{numbers[0]}"/>
</bean>
Q4. Demonstrate inline lists and inline maps in SpEL.
<bean id="collectionBean" class="com.example.CollectionBean">
<property name="fruits" value="#{'[\'Apple\', \'Banana\', \'Mango\']'}"/>
<property name="capitals" value="#{{'India':'New Delhi', 'USA':'Washington'}}"/>
</bean>
Q5. Evaluate static method call using SpEL.
<bean id="mathBean" class="com.example.MathBean">
<property name="piValue" value="#{T(java.lang.Math).PI}"/>
<property name="squareRoot" value="#{T(java.lang.Math).sqrt(49)}"/>
</bean>
✅ This covers:
·
SpEL Evaluation
·
Expressions in Bean Definitions
·
Literals, Properties
·
Arrays, Lists, Maps
·
Indexers
·
Inline Lists & Inline Maps
Unit-4: Data Access
1. Long Answer Questions (Descriptive)
1. Explain
the architecture of Spring JDBC and its advantages over
traditional JDBC.
2. Describe
the role of JDBC Template in the Spring Framework. Provide a
detailed example.
3. How
does Spring manage database connections? Explain the use of DataSource
.
4. Discuss
the concept of exception translation in Spring JDBC.
5. Explain
different methods provided by the JdbcTemplate class (e.g., query()
, update()
,
execute()
).
6. What
are JDBC Batch operations? How are they implemented in Spring?
7. Compare
JdbcTemplate with NamedParameterJdbcTemplate
in Spring.
8. Describe
the steps involved in performing CRUD operations using Spring
JDBC.
9. How
does Spring provide transaction management in JDBC?
10. Write a
note on best practices while working with Spring JDBC.
2. Short Answer Questions
1. What
is Spring JDBC?
2. Mention
one advantage of Spring JDBC over plain JDBC.
3. What
is the purpose of JdbcTemplate
?
4. Define
DataSource
in Spring JDBC.
5. What
is exception translation in Spring JDBC?
6. Which
method is used in JdbcTemplate
for retrieving multiple rows?
7. What
is a RowMapper?
8. Write
a use of batchUpdate()
in Spring
JDBC.
9. What
are the two templates commonly used in Spring JDBC?
10. Does Spring
JDBC support transactions? (Yes/No)
3. Multiple Choice Questions (MCQs)
1. Which
class is the central class in Spring JDBC?
a) JdbcDriver
b) JdbcTemplate
c) ConnectionFactory
d) JdbcHelper
Answer: b) JdbcTemplate
2. Which
interface is used for connection pooling in Spring JDBC?
a) Connection
b) DataSource
c) JdbcConnection
d) JdbcHelper
Answer: b) DataSource
3. Which
method of JdbcTemplate
is used to
perform INSERT/UPDATE/DELETE operations?
a) query()
b) execute()
c) update()
d) batchUpdate()
Answer: c) update()
4. Which
class is used for named parameters in SQL queries in Spring
JDBC?
a) NamedParameterJdbcTemplate
b) JdbcMapper
c) SqlParameterTemplate
d) JdbcHelper
Answer: a) NamedParameterJdbcTemplate
5. What
does the queryForObject()
method
return?
a) List of objects
b) Single object
c) ResultSet
d) Integer only
Answer: b) Single object
6. Which
method is used for batch operations in Spring JDBC?
a) executeBatch()
b) batchUpdate()
c) updateBatch()
d) multiUpdate()
Answer: b) batchUpdate()
7. Which
of the following is NOT a feature of Spring JDBC?
a) Exception Translation
b) Template-based approach
c) Automatic query optimization
d) Simplified connection management
Answer: c) Automatic query optimization
8. In
Spring JDBC, SQL exceptions are converted into:
a) Checked Exceptions
b) Runtime Exceptions
c) IO Exceptions
d) Compilation Errors
Answer: b) Runtime Exceptions
4. Fill in the Blanks
1. The
central class for JDBC operations in Spring is _______.
Answer: JdbcTemplate
2. A
_______ provides database connections in Spring JDBC.
Answer: DataSource
3. The
method used for DML operations in JdbcTemplate is _______.
Answer: update()
4. The
method used to fetch a single row is _______.
Answer: queryForObject()
5. _______
interface is used to map rows of a ResultSet.
Answer: RowMapper
6. The
method used for batch processing is _______.
Answer: batchUpdate()
7. Spring
translates SQL exceptions into _______ exceptions.
Answer: Runtime
8. _______
is an alternative to JdbcTemplate that allows named parameters.
Answer: NamedParameterJdbcTemplate
9. _______
provides a standard way of obtaining database connections.
Answer: DataSource
10. _______
is used to execute arbitrary SQL statements in Spring JDBC.
Answer: execute()
5. Programming Questions
Q1. Example of JdbcTemplate with Select Query
@Autowired
JdbcTemplate jdbcTemplate;
public List<Student> getAllStudents() {
return jdbcTemplate.query("SELECT * FROM student",
(rs, rowNum) -> new Student(
rs.getInt("id"),
rs.getString("name"),
rs.getInt("age")));
}
Q2. Insert record using JdbcTemplate update()
public int insertStudent(int id, String name, int age) {
String sql = "INSERT INTO student (id, name, age) VALUES (?, ?, ?)";
return jdbcTemplate.update(sql, id, name, age);
}
Q3. Using NamedParameterJdbcTemplate
@Autowired
NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public int updateStudentAge(int id, int age) {
String sql = "UPDATE student SET age=:age WHERE id=:id";
Map<String, Object> params = new HashMap<>();
params.put("id", id);
params.put("age", age);
return namedParameterJdbcTemplate.update(sql, params);
}
Q4. Batch Insert using batchUpdate()
public int[] batchInsert(List<Student> students) {
String sql = "INSERT INTO student (id, name, age) VALUES (?, ?, ?)";
return jdbcTemplate.batchUpdate(sql, students, students.size(),
(ps, student) -> {
ps.setInt(1, student.getId());
ps.setString(2, student.getName());
ps.setInt(3, student.getAge());
});
}
Q5. Configuring DataSource Bean in Spring
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
✅ This covers:
·
Spring JDBC Overview
·
JdbcTemplate Core Class
·
Database Connection Handling
·
Batch Operations