Mid Api
Mid Api
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.
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 {
CustomerService.java
package com.infy.service;
CustomerServiceImpl.java
package com.infy.service;
import com.infy.repository.CustomerRepository;
this.count = count;
this.repository = repository;
return repository.createCustomer();
CustomerRepository.java
package com.infy.repository;
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;
System.out.println(service.fetchCustomer());
context.close();
Output:
• 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(..))")
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.
6.Build a Spring Boot application that uses Spring Data JPA for database access.
Consider the InfyTel scenario, create an application to perform the following operations using Spring Data
JPA:
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.
1. <dependency>
2. <groupId>org.springframework.boot</groupId>
3. <artifactId>spring-boot-starter-data-jpa</artifactId>
4. </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. 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.
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.
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.
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.
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.
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.
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.