You are on page 1of 18

1.List and explain the various modules available in the Spring Framework.

Spring Framework 5.x has the following key module groups:


• Core Container: These are core modules that provide key features of the Spring framework.
• Data Access/Integration: These modules support JDBC and ORM data access approaches in Spring
applications.
• Web: These modules provide support to implement web applications.
• Others: Spring also provides few other modules such as the Test for testing Spring applications.
Core Container of Spring framework provides the Spring IoC container and Dependency Injection
features.

Core container has the following modules:


• Core: This is the key module of Spring Framework which provides fundamental support on which all
other modules of the framework are dependent.
• Bean: This module provides a basic Spring container called Bean Factory.
• Context: This module provides one more Spring container called Application Context which inherits
the basic features of the Bean Factory container and also provides additional features to support
enterprise application development.
• Spring Expression Language (SpEL): This module is used for querying/manipulating object values.
• AOP (Aspect Oriented Programming) and aspects: These modules help in isolating cross-cutting
functionality from business logic.
The Data Access/Integration module of Spring provides different data access approaches.
The following modules support Data Access/Integration:
• Java Database Connectivity (JDBC): It provides an abstract layer to support JDBC calls to relational
databases.
• Object Relational Mapping (ORM): It provides integration support for popular ORM(Object
Relational Mapping) solutions such as Hibernate, JPA, etc.
• Transactions: It provides a simple transaction API which abstracts the complexity of underlying
repository specific transaction API's from the application.
Spring Framework Web module provides basic support for web application development. The Web
module has a web application context that is built on the application context of the core container. Web
module provides complete Model-View-Controller(MVC) implementation to develop a presentation
tier of the application and also supports a simpler way to implement RESTful web services.

Spring Framework provides the following modules to support web application development:
• Web: This module has a container called web application context which inherits basic features from
Application Context container and adds features to develop web based applications.
• Webmvc: It provides the implementation of the MVC(model-view-controller) pattern to implement
the serverside presentation layer and also supports features to implement RESTful Web Services.
• WebFlux: Spring 5.0 introduced a reactive stack with a web framework called Spring WebFlux to
support Reactive programming in Spring's web layer and runs on containers such as Netty, Undertow,
and Servlet 3.1+.
• WebSocket: It is used for 2 way communication between client and server in WebSocket based web
applications.
Spring Framework has few additional modules, test module is one of the most commonly used ones
for testing Spring applications

• Test: This module provides the required support to test Spring applications using TestNG or
JUnit

2.Explain the functioning of Dependency Injection within the Spring framework and its
significance.

Benefits of Dependency Injection(DI):


• Helps to create loosely coupled application architecture facilitating re-usability and easy testing.
• Separation of responsibility by keeping code and configuration separately. Hence dependencies can
be easily modified using configuration without changing the code.
• Allows to replace actual objects with mock objects for testing, this improves testability by writing
simple JUnit tests that use mock objects.
The core container module of the Spring Framework provides IoC using Dependency Injection.
The Spring container knows which objects to create and when to create through the additional details
that we provide in our application called Configuration Metadata.
1. Application logic is provided through POJO classes.
2. Configuration metadata consists of bean definitions that the container must manage.
3. IoC container produces objects required by the application using POJO classes and configuration
metadata. IoC container is of two types – Bean Factory and Application Context.
BeanFactory:
• It is the basic Spring container with features to instantiate, configure and manage the beans.
• org.springframework.beans.factory.BeanFactory is the main interface representing a BeanFactory
container.
ApplicationContext:
• ApplicationContext is another Spring container that is more commonly used in Spring applications.
• org.springframework.context.ApplicationContext is the main Interface representing an
ApplicationContext container.
• It inherits the BeanFactory features and provides added features to support enterprise services such as
internationalization, validation, etc. ApplicationContext is the preferred container for Spring application
development.

Spring container uses one of these two ways to initialize the properties:

• Constructor Injection: This is achieved when the container invokes a parameterized constructor to
initialize the properties of a class

SpringConfiguration .java

package com.infy.util;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import com.infy.repository.CustomerRepository;

import com.infy.service.CustomerServiceImpl;

@Configuration
public class SpringConfiguration {

@Bean // Constructor Injection

public CustomerServiceImpl customerService() {

return new CustomerServiceImpl(customerRepository(), 20);

@Bean // Constructor Injection

public CustomerRepository customerRepository() {

return new CustomerRepository();

CustomerService.java

package com.infy.service;

public interface CustomerService {

public String fetchCustomer();

public String createCustomer();

CustomerServiceImpl.java

package com.infy.service;

import com.infy.repository.CustomerRepository;

public class CustomerServiceImpl implements CustomerService {

private int count;

private CustomerRepository repository;

public CustomerServiceImpl(CustomerRepository repository, int count) {

this.count = count;

this.repository = repository;

public String fetchCustomer() {


return repository.fetchCustomer(count);

public String createCustomer() {

return repository.createCustomer();

CustomerRepository.java

package com.infy.repository;

public class CustomerRepository {

public String fetchCustomer(int count) {

return " The no of customers fetched are : " + count;

public String createCustomer() {

return "Customer is successfully created";

Client.java

package com.infy;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import org.springframework.context.support.AbstractApplicationContext;

import com.infy.service.CustomerServiceImpl;

import com.infy.util.SpringConfiguration;

public class Client {

public static void main(String[] args) {

CustomerServiceImpl service = null;

AbstractApplicationContext context = new


AnnotationConfigApplicationContext(SpringConfiguration.class);
service = (CustomerServiceImpl) context.getBean("customerService");

System.out.println(service.fetchCustomer());

context.close();

Output:

The no of customers fetched are : 20

• Setter Injection: This is achieved when the container invokes setter methods of a class to initialize
the properties after invoking a default constructor.

3.How can you configure an IoC (Inversion of Control) container using Java-based
configuration in Spring? Explain in detail.

The Java-based configuration metadata is provided in the Java class using the following annotations:

@Configuration: The Java configuration class is marked with this annotation. This annotation identifies
this as a configuration class, and it’s expected to contain details on beans that are to be created in the Spring
application context.

@Bean: This annotation is used to declare a bean. The methods of configuration class that creates an
instance of the desired bean are annotated with this annotation. These methods are called by the Spring
containers during bootstrap and the values returned by these methods are treated as Spring beans. By default,
only one bean instance is created for a bean definition by the Spring Container, and that instance is used by
the container for the whole application lifetime.

For example, the SpringConfiguration class can be configured in a Java class using the above annotations as
follows :

1. @Configuration
2.
3. public class SpringConfiguration {
4.
5. @Bean
6. public CustomerServiceImpl customerService() {
7.
8. return new CustomerServiceImpl();
9. }
10. }

11.
By default, the bean name is the same as the name of the method in which the bean is configured. So in the
above code bean name is customerService. If you want to change the bean name then you can either rename
the method or provide a different name with the name attribute as follows:

1. @Configuration
2. public class SpringConfiguration {
3.
4. @Bean(name="service")
5. public CustomerServiceImpl customerService() {
6.
7. return new CustomerServiceImpl();
8. }
9. }

10.

4.What is Spring AOP, and how does it enhance software modularity? Develop an aspect
using Spring AOP to handle cross cutting concerns in an application

AOP (Aspect Oriented Programming) is used for applying common behaviors like transactions, security,
logging, etc. to the application.

These common behaviors generally need to be called from multiple locations in an application. Hence, they
are also called as cross cutting concerns in AOP.

Spring AOP provides the solution to cross cutting concerns in a modularized and loosely coupled way.

• In Spring AOP, we need to modularize and define each of the cross cutting concerns in a single
class called Aspect.
• Each method of the Aspect which provides the implementation for the cross cutting concern is called
Advice.
• The business methods of the program before or after which the advice can be called is known as
a Joinpoint.
• The advice does not get inserted at every Joinpoint in the program.
• An Advice gets applied only to the Joinpoints that satisfy the Pointcut defined for the advice.
• Pointcut represents an expression that evaluates the business method name before or after which
the advice needs to be called.

Before Advice:

@Before("execution(* com.infy.service.CustomerServiceImpl.fetchCustomer(..))")

public void logBeforeAdvice(JoinPoint joinPoint) {

logger.info("In Before Advice, Joinpoint signature :{}", joinPoint.getSignature());

long time = System.currentTimeMillis();

String date = DateFormat.getDateTimeInstance().format(time);

logger.info("Report generated at time:{}", date);


}

After Advice:

@After("execution(* com.infy.service.CustomerServiceImpl.fetchCustomer(..))")
public void logAfterAdvice(JoinPoint joinPoint) {
logger.info("In After Advice, Joinpoint signature :{}", joinPoint.getSignature());
long time = System.currentTimeMillis();
String date = DateFormat.getDateTimeInstance().format(time);
logger.info("Report generated at time {}", date);
}
5.Demonstrate Autowiring by injecting dependencies into Spring components.
In Spring if one bean class is dependent on another bean class then the bean dependencies need to be
explicitly defined in your configuration class. But you can let the Spring IoC container to inject the
dependencies into dependent bean classes without been defined in your configuration class. This is called
as autowiring.
To do autowiring, you can use @Autowired annotation. This annotation allows the Spring IoC container to
resolve and inject dependencies into your bean.@Autowired annotation performs byType Autowiring i.e.
dependency is injected based on bean type. It can be applied to attributes, constructors, setter methods of a
bean class.

Examples of the autowiring dependencies

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


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

6.Build a Spring Boot application that uses Spring Data JPA for database access.

Demo 3: InfyTel Application development using Spring Data JPA


Highlights:

• To understand key concepts and configuration of Spring Data JPA


• To perform CRUD operations using Spring Data JPA

Consider the InfyTel scenario, create an application to perform the following operations using Spring Data
JPA:

• Insert customer details


• Delete customer for given phone number
• Find customer for a given phone number
• Update customer for a given phone number

While generating the Spring Boot Maven project from Spring initializer, Select "Spring Data JPA" and
"MySQL Driver" dependency.

Note: This screen keeps changing depending on updates from Pivotal and change in the Spring Boot version.

Spring Data JPA Dependency:

1. <dependency>
2. <groupId>org.springframework.boot</groupId>
3. <artifactId>spring-boot-starter-data-jpa</artifactId>

4. </dependency>

MySQL Driver dependency:

1. <dependency>
2. <groupId>mysql</groupId>
3. <artifactId>mysql-connector-java</artifactId>
4. <scope>runtime</scope>

5. </dependency>

Note that the version number of the jars is not defined here as it can be determined by spring-boot-starter-
parent. Once you have properly configured your maven project our pom.xml will look as below:

pom.xml:

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


2. <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
4.0.0.xsd">
4. <modelVersion>4.0.0</modelVersion>
5. <parent>
6. <groupId>org.springframework.boot</groupId>
7. <artifactId>spring-boot-starter-parent</artifactId>
8. <version>2.2.5.RELEASE</version>
9. <relativePath/> <!-- lookup parent from repository -->
10. </parent>
11. <groupId>com.infyTel</groupId>
12. <artifactId>demo-jpa-insertdelete</artifactId>
13. <version>0.0.1-SNAPSHOT</version>
14. <name>demo-jpa-insertdelete</name>
15. <description>Spring Boot project to demonstrate insert and delete operation using Spring Data
JPA</description>
16.
17. <properties>
18. <java.version>1.8</java.version>
19. </properties>
20.
21. <dependencies>
22. <dependency>
23. <groupId>org.springframework.boot</groupId>
24. <artifactId>spring-boot-starter-data-jpa</artifactId>
25. </dependency>
26.
27. <dependency>
28. <groupId>mysql</groupId>
29. <artifactId>mysql-connector-java</artifactId>
30. <scope>runtime</scope>
31. </dependency>
32. <dependency>
33. <groupId>log4j</groupId>
34. <artifactId>log4j</artifactId>
35. <version>1.2.17</version>
36. </dependency>
37. <dependency>
38. <groupId>org.springframework.boot</groupId>
39. <artifactId>spring-boot-starter-test</artifactId>
40. <scope>test</scope>
41. <exclusions>
42. <exclusion>
43. <groupId>org.junit.vintage</groupId>
44. <artifactId>junit-vintage-engine</artifactId>
45. </exclusion>
46. </exclusions>
47. </dependency>
48. </dependencies>
49.
50. <build>
51. <plugins>
52. <plugin>
53. <groupId>org.springframework.boot</groupId>
54. <artifactId>spring-boot-maven-plugin</artifactId>
55. </plugin>
56. </plugins>
57. </build>
58.
59. </project>
60.

Step 1: Create an Entity class "Customer.java" as shown below:

1. package com.infyTel.domain;
2.
3. import javax.persistence.Column;
4. import javax.persistence.Entity;
5. import javax.persistence.Id;
6.
7. @Entity
8. public class Customer {
9.
10. @Id
11. @Column(name = "phone_no")
12. private Long phoneNumber;
13. private String name;
14. private Integer age;
15. private Character gender;
16. private String address;
17. @Column(name = "plan_id")
18. private Integer planId;
19.
20. public Customer() {}
21.
22. public Customer(Long phoneNumber, String name, Integer age, Character gender, String
address, Integer planId) {
23. super();
24. this.phoneNumber = phoneNumber;
25. this.name = name;
26. this.age = age;
27. this.gender = gender;
28. this.address = address;
29. this.planId = planId;
30. }
31. public Long getPhoneNumber() {
32. return phoneNumber;
33. }
34. public void setPhoneNumber(Long phoneNumber) {
35. this.phoneNumber = phoneNumber;
36. }
37. public String getName() {
38. return name;
39. }
40. public void setName(String name) {
41. this.name = name;
42. }
43. public Integer getAge() {
44. return age;
45. }
46. public void setAge(Integer age) {
47. this.age = age;
48. }
49. public Character getGender() {
50. return gender;
51. }
52. public void setGender(Character gender) {
53. this.gender = gender;
54. }
55. public String getAddress() {
56. return address;
57. }
58. public void setAddress(String address) {
59. this.address = address;
60. }
61. public Integer getPlanId() {
62. return planId;
63. }
64. public void setPlanId(Integer planId) {
65. this.planId = planId;
66. }
67. @Override
68. public String toString() {
69. return "Customer [phoneNumber=" + phoneNumber + ", name=" + name + ", age="
+ age + ", gender=" + gender
70. + ", address=" + address + ", planId=" + planId + "]";
71. }
72. public static CustomerDTO prepareCustomerDTO(Customer customer)
73. {
74. CustomerDTO customerDTO = new CustomerDTO();
75. customerDTO.setPhoneNumber(customer.getPhoneNumber());
76. customerDTO.setName(customer.getName());
77. customerDTO.setGender(customer.getGender());
78. customerDTO.setAge(customer.getAge());
79. customerDTO.setAddress(customer.getAddress());
80. customerDTO.setPlanId(customer.getPlanId());
81. return customerDTO;
82.
83. }
84.
85. }
86.

87.

Step 2: Create a DTO class "CustomerDTO.java" as shown below:

1. package com.infyTel.dto;
2.
3. import com.infyTel.domain.Customer;
4.
5. public class CustomerDTO {
6.
7.
8. private Long phoneNumber;
9. private String name;
10. private Integer age;
11. private Character gender;
12. private String address;
13. private Integer planId;
14.
15. public CustomerDTO() {}
16.
17. public CustomerDTO(Long phoneNumber, String name, Integer age, Character gender, String
address, Integer planId) {
18. super();
19. this.phoneNumber = phoneNumber;
20. this.name = name;
21. this.age = age;
22. this.gender = gender;
23. this.address = address;
24. this.planId = planId;
25. }
26. public Long getPhoneNumber() {
27. return phoneNumber;
28. }
29. public void setPhoneNumber(Long phoneNumber) {
30. this.phoneNumber = phoneNumber;
31. }
32. public String getName() {
33. return name;
34. }
35. public void setName(String name) {
36. this.name = name;
37. }
38. public Integer getAge() {
39. return age;
40. }
41. public void setAge(Integer age) {
42. this.age = age;
43. }
44. public Character getGender() {
45. return gender;
46. }
47. public void setGender(Character gender) {
48. this.gender = gender;
49. }
50. public String getAddress() {
51. return address;
52. }
53. public void setAddress(String address) {
54. this.address = address;
55. }
56. public Integer getPlanId() {
57. return planId;
58. }
59. public void setPlanId(Integer planId) {
60. this.planId = planId;
61. }
62. @Override
63. public String toString() {
64. return "Customer [phoneNumber=" + phoneNumber + ", name=" + name + ", age="
+ age + ", gender=" + gender
65. + ", address=" + address + ", planId=" + planId + "]";
66. }
67.
68. public static Customer prepareCustomerEntity(CustomerDTO customerDTO)
69. {
70. Customer customerEntity = new Customer();
71. customerEntity.setPhoneNumber(customerDTO.getPhoneNumber());
72. customerEntity.setName(customerDTO.getName());
73. customerEntity.setGender(customerDTO.getGender());
74. customerEntity.setAge(customerDTO.getAge());
75. customerEntity.setAddress(customerDTO.getAddress());
76. customerEntity.setPlanId(customerDTO.getPlanId());
77. return customerEntity;
78.
79. }
80. }

81.

Step 3: Create an interface "CustomerService.java" as shown below:

1. package com.infyTel.service;
2.
3. import com.infyTel.dto.CustomerDTO;
4.
5. public interface CustomerService {
6.
7. public void insertCustomer(CustomerDTO Customer) ;
8. public void removeCustomer(Long phoneNo);
9. public CustomerDTO getCustomer(Long phoneNo);
10. public String updateCustomer(Long phoneNo,Integer newPlanId);
11. }

12.

Step 4: Create a service class "CustomerServiceImpl.java" as shown below:

1. package com.infyTel.service;
2.
3. import java.util.Optional;
4.
5. import org.springframework.beans.factory.annotation.Autowired;
6. import org.springframework.stereotype.Service;
7.
8. import com.infyTel.domain.Customer;
9. import com.infyTel.dto.CustomerDTO;
10. import com.infyTel.repository.CustomerRepository;
11.
12. @Service("customerService")
13. public class CustomerServiceImpl implements CustomerService {
14. @Autowired
15. private CustomerRepository repository;
16.
17. @Override
18. public void insertCustomer(CustomerDTO customer) {
19. repository.saveAndFlush(CustomerDTO.prepareCustomerEntity(customer));
20.
21. }
22.
23. @Override
24. public void removeCustomer(Long phoneNo) {
25. repository.deleteById(phoneNo);
26.
27. }
28.
29. @Override
30. public CustomerDTO getCustomer(Long phoneNo) {
31. Optional<Customer> optionalCustomer = repository.findById(phoneNo);
32. Customer customerEntity = optionalCustomer.get();// Converting
Optional<Customer> to Customer
33. CustomerDTO customerDTO = Customer.prepareCustomerDTO(customerEntity);
34. return customerDTO;
35. }
36.
37. @Override
38. public String updateCustomer(Long phoneNo, Integer newPlanId) {
39. Optional<Customer> optionalCustomer = repository.findById(phoneNo);
40. Customer customerEntity = optionalCustomer.get();
41. customerEntity.setPlanId(newPlanId);
42. repository.save(customerEntity);
43. return "The plan for the customer with phone Number :" + phoneNo + " has been
updated successfully.";
44. }
45.
46. }

47.

Step 5: Create an interface “CustomerRepository.java” as shown below:

1. package com.infyTel.repository;
2.
3. import org.springframework.data.jpa.repository.JpaRepository;
4.
5. import com.infyTel.domain.Customer;
6.
7. public interface CustomerRepository extends JpaRepository<Customer, Long>{
8.
9. }

10.

Step 6: Update "application.properties" as shown below:

1. spring.datasource.url = jdbc:mysql://localhost:3306/sample
2. spring.datasource.username = root
3. spring.datasource.password = root
4. spring.jpa.generate-ddl=true

5.

Step 7: Create a class “Client.java” as shown below:

1. package com.infyTel;
2.
3. import java.util.Scanner;
4. import org.apache.log4j.Logger;
5. import org.springframework.beans.factory.annotation.Autowired;
6. import org.springframework.boot.CommandLineRunner;
7. import org.springframework.boot.SpringApplication;
8. import org.springframework.boot.autoconfigure.SpringBootApplication;
9. import org.springframework.context.ApplicationContext;
10.
11. import com.infyTel.dto.CustomerDTO;
12. import com.infyTel.service.CustomerService;
13.
14. @SpringBootApplication
15. public class Client implements CommandLineRunner{
16. static Logger logger = Logger.getLogger(Client.class);
17. @Autowired
18. ApplicationContext context;
19. @Autowired
20. CustomerService service;
21.
22. public static void main(String[] args) {
23. SpringApplication.run(Client.class, args);
24. }
25.
26. @Override
27. public void run(String... args) throws Exception {
28.
29.
30. CustomerDTO customer1= new CustomerDTO(7022713754L, "Adam", 27, 'M',
"Chicago", 1);
31. CustomerDTO customer2= new CustomerDTO(7022713744L, "Susan", 27, 'F',
"Alberta", 2);
32. CustomerDTO customer3= new CustomerDTO(7022713722L, "Lucy", 27, 'F',
"MUMBAI", 3);
33.
34. //invoke service layer method to insert Customer
35. service.insertCustomer(customer1);
36. service.insertCustomer(customer2);
37. service.insertCustomer(customer3);
38. logger.info("Records are successfully added..");
39.
40. System.out.println("Enter the phone Number of the Customer which has to be
deleted.");
41. Scanner scanner = new Scanner(System.in);
42. Long phoneNo = scanner.nextLong();
43.
44. // Invoking Service layer method to remove Customer details from
45. // Customer table
46. service.removeCustomer(phoneNo);
47. logger.info("Record Deleted");
48.
49. logger.info("Let's print the details of a Customer");
50. System.out.println("Enter the phone Number of the Customer whose details have to
be printed.");
51. Long phoneNo1 = scanner.nextLong();
52. CustomerDTO customerDTO = service.getCustomer(phoneNo1);
53. logger.info("Customer Details:");
54. logger.info("Phone Number : "+customerDTO.getPhoneNumber());
55. logger.info("Name : "+customerDTO.getName());
56. logger.info("Age : "+customerDTO.getAge());
57. logger.info("Gender : "+customerDTO.getAge());
58. logger.info("Address : "+customerDTO.getAddress());
59. logger.info("Plan ID : "+customerDTO.getPlanId());
60.
61. logger.info("Let's update the current plan of a Customer");
62. System.out.println("Enter the phone Number of the Customer whose current plan has
to be updated.");
63. Long phoneNo2 = scanner.nextLong();
64. System.out.println("Enter the new plan id for the Customer");
65. Integer newPlanId = scanner.nextInt();
66. String msg = service.updateCustomer(phoneNo2, newPlanId);
67. logger.info(msg);
68. scanner.close();
69.
70.
71. }
72.
73.
74. }
75.

76.

Run the Client.java as "Spring Boot App".

Expected output on the Console:

You might also like