InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
What is ELK stack? |
|
Answer» Popular logging frameworks such as Log4j, Logback, and SLF4J, etc. provide logging functionality for the individual microservice application. However, when a group of run together to provide complete business functionality, it becomes really challenging to TRACE a request across all the services, especially in case of failures. Hence it is highly recommended to have a centralized logging solution in place, to have all the log messages stored in a central location rather than on local machine/container of each microservice. This eliminates dependency on the local disk space (volumes) and can HELP retain the logs for a long time for analysis in the future. The Elasticsearch, Logstash, and Kibana tools, collectively known as the ELK stack, provide an end-to-end logging solution in the distributed application; providing a centralized logging solution. ELK stack is one of the most commonly used architectures for custom logging management in cloud-based Microservices applications. Elasticsearch is a NoSQL database used to store the logs as documents. Logstash is a log pipeline tool that accepts logs as input from various micro service applications, executes transformations if required and stores data into the target (Elasticsearch database). Kibana is a UI that works on top of Elasticsearch, providing a VISUAL representation of the logs and ability to search them as required. All three tools are typically installed on a single server, known as the ELK server. In a centralized logging approach, applications should follow a standard for log messages. Each log message having a context, message, and correlation ID. The context information is ideally can be the IP address, user information, process details, timestamp, etc. The message is a simple text description of the SCENARIO. The correlation ID is dynamically generated and is common across all that used for end-to-end TRACKING of a request/task. |
|
| 2. |
What is Cloud Foundry? |
|
Answer» CLOUD Foundry is an open source cloud PaaS (platform as a service) where developers and organizations can build, deploy, run and scale their applications. It is the same company that manages Spring, hence has great support for running Spring based cloud applications. For deploying an application in Cloud Foundry, we need to configure the application with a target and a space to deploy the application to. It is increasingly GAINING popularity as an open source and lets US use our own tools and code. Organizations can deploy Cloud Foundry PaaS on their own internal infrastructure; on cloud PROVIDERS' infrastructure, such as Amazon Web Services (AWS) or Microsoft Azure. It also provides a few out of the box components:
It is very easy to set up and application on Cloud Foundry:
|
|
| 3. |
What is Reactive Programming? How it can be enabled using Spring? |
|
Answer» Traditional monolithic applications developed in the last few decades had the luxury of CONSIDERABLE response time, multiple hours of offline maintenance and smaller volumes of data. However, this is not acceptable with the modern applications serving high volumes round the clock with an expectation of sub-second response time with 100% availability. Reactive programming is ONE of the solutions for the above constraints, which is rapidly gaining popularity in cloud-based applications. It is a programming pattern that RECOMMENDS an asynchronous, non-blocking, event-driven approach for data processing. In the reactive style of programming, after making a request for the resource, the application continues to perform other tasks instead of WAITING for the response. When the data is available, the application should get the notification along with data in the form of call back function which handles the response as per business needs. Systems built as Reactive Systems are highly flexible, loosely coupled, and scalable. This makes them easier to develop and responsive to change. They are significantly more resilient and are able to handle failures gracefully. They are quite responsive and ideal for interactive applications. Spring Web Reactive brings reactive capabilities for web applications, which is based on the same fundamental programming model as Spring MVC. The base API is 'Reactive HTTP' as opposed to 'Servlet API' and runs only on Servlet Containers like Netty or Undertow. We need to add 'spring-boot-starter-webflux' to ENABLE Spring Reactive and 'spring-boot-starter-reactor-netty' as the default embedded reactive server; in the application dependencies. Creating a Spring Reactive Controller is similar to a typical Spring MVC Controller using @RestController and the required @RequestMapping annotations. |
|
| 4. |
What is Service Discovery and how it can be enabled in Spring Boot? |
|
Answer» In a typical Microservice architecture multiple services collaborate to provide an overall functionality. These set of service instances may have dynamically assigned network locations. Also, the services scale up and down as per the load. It could get tricky in a cloud environment resolving the services that are required for operation for common functionality. Consequently, in order for a client to make a request to a service, it must use a service-discovery mechanism. It is the process where services register with a CENTRAL registry and other services query this registry for resolving dependencies. A service registry is a highly available and up to date database containing the network locations of service instances. The two main service-discovery components are client-side discovery and service-side discovery. Netflix Eureka is one of the POPULAR Service Discovery Server and Client tools. Spring Cloud SUPPORTS several ANNOTATIONS for enabling service discovery. @EnableDiscoveryClient annotation allows the applications to query Discovery server to find required services. In Kubernetes environments, service discovery is built-in, and it performs service INSTANCE registration and deregistration. |
|
| 5. |
What is Hystrix and how it can be implemented in the Spring Boot application? |
|
Answer» Netflix’s Hystrix is a library that provides an implementation of the Circuit BREAKER pattern for Microservices based applications. A circuit breaker is a pattern that monitors for failures and once the failures reach a certain threshold, the circuit breaker TRIPS, and all further calls will return with an error, without the external call being made at all. On applying Hystrix circuit breaker to a method, it watches for failing calls to that method, and if failures build up to a threshold; Hystrix opens the circuit so that subsequent calls automatically fail. While the circuit is open, Hystrix redirects call to a specified method called a fallback method. This creates a time buffer for the related service to recover from its failing state. Below are the annotations used to enable Hystrix in a Spring Boot application: @EnableCircuitBreaker: It is added to the main Application class for enabling Hystrix as a circuit breaker and to enable hystrix-javanica; which is a wrapper around native Hystrix required for using the annotations. @HystrixCommand: This is method annotation that notifies Spring to wrap a particular method in a proxy connected to a circuit breaker so that Hystrix can monitor it. We also need to define a fallback method having the backup logic that needs to be EXECUTED in the failure scenario. Hystrix passes the control to this fallback method when the circuit is broken. This annotation can also be used for asynchronous requests. Currently, it works only with classes marked with @COMPONENT or @Service. |
|
| 6. |
What is Spring Cloud Contract? |
|
Answer» Spring Cloud Contract implements the Consumer Driven Contracts (CDC) approach via the 'Spring Cloud Contract VERIFIER' project. Consumer Driven Contracts is a software DEVELOPMENT and evolution approach where each consumer of SERVICE develops a contract that contains the consumer's expectations about the APIs provided by Service. The full collection of all of the consumers' contracts constitutes the requirement SET for the service. Once the service owners have all of the contracts for their consumers, the service owners can develop a test suite that VERIFIES the service APIs. This test suite provides rapid feedback about failures when the service changes. In Spring Cloud Contract, a "producer" is the owner of an API and a "consumer" is the user of an API. Service A (as a consumer) creates a contract that service B (as a producer) will have to abide by. This contract acts as the invisible glue between services - even though they live in separate code bases and run on different JVMs. Breaking changes can be detected immediately during build time. |
|
| 7. |
What is Microservices? How it is different from monolithic applications? |
|
Answer» Microservices (MS) is an architecture pattern that prescribes to divide an application based on business functionality instead of technical boundaries. These set of smaller interconnected services constitute the complete application. As opposed to monolithic architecture, it recommends breaking the application into smaller atomic units, each performing a single function. Typically, an application provides a set of distinct features or functionality, such as order management, billing, customer service, ETC. Each microservice WORKS as a mini-application that has its own hexagonal architecture. It is often compared to Honeycombs (nests) that are a combination of MULTIPLE hexagonal structures. Below are some of the key features of Microservices that distinguish from monolithic:
|
|
| 8. |
What is @Autowired annotation? How is @Qualifier used with it? |
|
Answer» @Autowired ANNOTATION is used to AUTOWIRE i.e. inject dependent bean on the constructor, setter method or a field/property. When @Autowired is used on dependency, the application context searches for a matching dependency and provides as required. This helps us to avoid writing EXPLICIT injection logic. However, by default, all dependencies that are Autowired are required. So, in scenarios where a required dependency is not available or if there is conflict; it results in an exception like NoUniqueBeanDefinitionException. There are a few options available to turn off the default behavior:
@Autowired (required=false) private Contract contractBean;
@Qualifier ("design") private Contract contractBean; |
|
| 9. |
Explain the difference between @Controller and @RestController annotation? |
|
Answer» Traditional Spring controllers are created by ADDING a class with @Controller annotation. It is actually a specialization of the @Component annotation that allows the implementation classes to be autodetected by Spring context through the CLASSPATH scanning. Generally, @Controller annotation is used in combination with @RequestMapping and @ResponseBody added to the request handling methods to define the REST APIS. @RestController is a convenient annotation that combines both the features of @Controller and @ResponseBody annotations. The KEY difference between typical Spring @Controller and the RESTful web service @RestController is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller returns the object and the object data is written directly to the HTTP response as JSON. |
|
| 10. |
What is HATEOS in RESTful applications? |
|
Answer» HATEOAS (Hypermedia as the Engine of Application State) is a principle for REST APIs, according to which the API should guide the client through the application by returning relevant information about potential subsequent steps, ALONG with the response. This information is in the form of hypermedia links included with responses, which helps the client to navigate the site's REST interfaces. It essentially tells the clients what they can do next, and what is the URI of the resource. If a service consumer can use the links from the response to perform transactions, then it would not need to hardcode all links. According to the Richardson Maturity Model, HATEOAS is considered the final level of REST. To support HATEOAS, each resource in the application should contain a "links" property which defines hyperlinks to related resources. Each link object TYPICALLY includes the following properties: "rel”: Relation with the TARGET resource. "href”: URI for resource For EXAMPLE: { "contractId": 10067, "description": "Contract details for the requested orderId", "status": "created", "links": [ { "rel": "self", "href": "HTTP://demoApplication.com/contracts/10067"}] } |
|
| 11. |
What is REST? How to build RESTful service using Spring Boot? |
|
Answer» REST stands for REpresentational State Transfer. It is a web standards-based architecture using HTTP Protocol for data communication. A REST Server provides access to resources and REST client accesses and modifies the resources. Resources can be TEXT FILES, HTML pages, images, videos or any dynamic business data. Each resource is identified by URIs/ global IDs. REST can use various representation to represent a resource like text, JSON, XML. Though in Spring Boot Microservices applications, JSON is the most popular one used. RESTful web services developed by applying REST architectural concept. RestTemplate is the core class for accessing Spring RESTful web services from the client-side. It communicates via HTTP server using RESTful constraints. We can build RESTful web service in Spring Boot by adding ‘spring-boot-starter-web’ starter pack in the classpath. We can then create a controller class to define all API (URL) and REST operations like GET, POST, etc. This class should be annotated with @RESTCONTROLLER, making the class return the OBJECT. In case we want to convert the response to JSON format then we need to add Jackson to the classpath. Along with Spring Boot’s embedded Tomcat server, we can have the REST server running via the application JAR. |
|
| 12. |
Can you highlight the difference between @RequestMapping, @RequestParam, @RequestBody, and @PathVariable annotations? |
|
Answer» @RequestMapping: This annotation is used on methods in the controller class to specify the API path and the REST operation type via RequestMethod. This method will be responsible for serving the HTTP request to the given path and RETURN the desired response with the help of desired service classes. Example: @RequestMapping(path = "/contract/1.0/contracts", method = RequestMethod.PUT) @RequestBody: This annotation is used to bind the incoming HTTP request body to the parameter defined in the method annotated with @RequestMapping. SPRING uses HTTP Message converters to convert the HTTP request body into a defined domain object @PathVariable: This annotation is used to get the value from the HTTP URL and capture into the method arguments. Example: @RequestMapping(path = "/products/{id}",produces = "application/json") @RequestParam: This annotation is used to capture values from the HTTP URL based on keys defined in the methods. Spring parse the request parameters and put the appropriate ONES into the method arguments. Example: @RequestMapping(path = "/products/{id}",produces = "application/json") public Product getPlan (@PathVariable("id") final String planId, @RequestParam(value = "q", required = false) final String queryParameters) |
|
| 13. |
What is the difference between Singleton and Prototype scope in Spring? |
|
Answer» While defining a bean, Spring allows us to declare the scope of that bean. The scope describes the life cycle and visibility of that bean in the APPLICATION context. Spring framework supports five scopes with the default scope as a singleton. The scope can be described using @Scope annotation on any spring bean: @Service @Scope("singleton") public CLASS ServiceImpl implements Service Singleton: When a bean is defined with a scope as Singleton, then the container creates only a single instance of that bean. A single object instance is cached and returned for all subsequent requests for this bean. On making any modifications to the object will be reflected in all references to the bean. This is the default scope when no other scope is specified. However, the singleton scope is one object per Spring container only. So, if we have multiple spring containers running on a single JVM, then there can be multiple instances of the same bean. A bean defined with prototype scope will return a different instance of an object, every time it is requested from the container. If a bean contains a state, it is recommended that you use the prototype scope for it. It can be defined by setting the VALUE ‘prototype’ to the @Scope annotation in the bean definition. We should use this scope when the object is not usable after a request is completed or requires certain state for each new request. |
|
| 14. |
How to implement Caching in Spring Boot? |
|
Answer» Caching is a mechanism that helps in REDUCING roundtrip calls to Database, REST service, files, etc. Performance under heavy load is a key feature expected from any modern web and mobile application, hence caching is really vital to enhance the speed of FETCHING data. Spring Boot provides a STARTER project for caching “spring-boot-starter-cache”, adding this to an application brings in all the dependencies to enable JSR-107 (JCACHE - Java Temporary Caching API) and Spring caching annotations. In order to enable caching in a Spring Boot application, we need to add @EnableCaching to the required configuration class. This will automatically configure a suitable CacheManager to serve as a provider for the cache. Example: @Configuration @EnableCaching public class CachingConfig { @Bean public CacheManager cacheManager() { RETURN new ConcurrentMapCacheManager("ADDRESSES"); } }Now to enable caching, we need to add a @Cacheable annotation to the methods where we want to cache the data. @Cacheable("addresses") public String getAddress(Customer customer) {...} |
|
| 15. |
When should you use @Component vs @Bean annotations? |
|
Answer» @Bean is used when we WANT to define a class method as a Spring bean producer. It is used in conjunction with a configuration class (annotated with @Configuration). Here we explicitly declare the Spring beans. On the other hand, @Component is used in classes, marking it as a source of bean definitions. However, it only works when we enable component scan in the application and the given class is included in it. So, in this case, we let Spring pick up the bean. Now the end-result for both annotations is the same as Spring will add the beans the context. However, there are some minor characteristics that can be considered while choosing between @Bean and @Component. Let us CONSIDER a scenario where we have a module containing few utility services, that are being shared across multiple applications. Though these services provide nice features, not all of them are needed by each application. Here, if mark these utility service classes as @Component and set them for component scan in the application, we might end up detecting more beans than necessary. In this case, we either have to adjust the filtering of the component scan or provide configurations where even the unused beans can run. In this scenario, it would be BETTER to use @Bean annotation and only instantiate the beans, that are REQUIRED INDIVIDUALLY in each application. In a nutshell, we should use @Bean for adding third-party classes to the context, whereas @Component when it is inside the same application. |
|
| 16. |
What Is a Circular Dependency? |
|
Answer» Circular Dependency in Spring is a situation when a bean depends on another bean, but at the same time, the other bean depends on the first one in turn. Now when the Spring context is trying to load all the beans, it tries to create beans in the order needed for them to work COMPLETELY. For EXAMPLE, if we have an application with three beans where bean X depends on bean Y and it depends on bean Z. Spring will create beans in a sequence where bean Z is first created, then create Y with Z been injected to it and FINALLY create X with Y being injected into it. bean X > bean Y > bean Z But, in case we have a circular dependency, where bean X depends on bean Y; but Y, in turn, depends on X again. bean X > bean Y > bean X Here Spring is unable to determine which bean should be created first since they depend on one another. In this case, Spring will throw a BeanCurrentlyInCreationException while loading the Application context. It can happen if dependencies are not defined properly while using CONSTRUCTOR injection as it requires to create and load all the dependencies while loading the context. Workarounds:
An appropriate redesign of the components in a manner that their hierarchy is well designed can avoid circular dependencies.
As setter-based injection loads the dependencies only when required; can help in avoiding error due to a circular dependency. @Autowired public VOID setY (Y y) { this.y = y; } |
|
| 17. |
What Is the Difference Between Hibernate and Spring Data JPA? |
|
Answer» Hibernate is a JPA (Java Persistence API) implementation providing ORM (Object-relational MAPPING) for mapping, storing, updating and retrieving application data from relational DATABASES to Java objects and vice versa. Hibernate maps Java classes to database tables and from Java data types to SQL data types, hence programmer is relieved from WRITING traditional data persistence programs like SQL. Whereas SPRING Data JPA is a JPA Data Access Abstraction used to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores. With Spring Data, we still need to use Hibernate, Eclipse Link, or any other JPA provider. One of the key benefits is that we can control transaction boundaries with the use of @Transactional annotation. |
|
| 18. |
What are Spring Profiles? How do you implement it using Spring Boot? |
|
Answer» A profile is a feature of Spring framework that allows us to MAP the beans and components to certain PROFILES. A profile can be assumed to be a group or an environment like dev, test, prod, etc.; that needs a certain kind of behavior and/or requires to maintain distinct functionalities across the profiles. So, when the application is running with ‘dev’ (Development) profile only certain beans can be loaded and when in ‘prod’ (Production) certain other beans can be loaded. In Spring Boot we use @Profile annotation to map bean to a PARTICULAR profile by taking the names of one (or multiple) profiles. Let’s say we have a COMPONENT class that is used to record and mock the REST requests and responses. However, we want to activate this component only in dev profile and disable in all other profiles. We annotate the bean with “dev” profile so that it will only be present in the container during development. @Component @Profile("dev") public class DevMockUtilityProfiles are activated using application.yml in the Spring project: spring.profiles.active=devTo set profiles programmatically, we can also use the SpringApplication class: SpringApplication.setAdditionalProfiles("dev"); |
|
| 19. |
What is Swagger? How do you implement for Spring Boot application? |
|
Answer» Swagger is a specification and framework implementation for producing a visual representation of RESTful Web Services API. With the help of Swagger, the API consumer can understand and interact with the remote service with a minimal amount of implementation logic. One can compare it to the blueprint of a house. It creates a contract for the RESTful API, detailing all of its resources and operations in a human and machine-readable format. It allows the documentation to be placed at the same project as the server allowing easy development, discovery, and INTEGRATION of the application. It is typically defined in a YAML file, which makes it easy to comprehend both by developers, API CLIENTS, and business users, ETC. Swagger can be integrated with Gradle for enabling code generation FEATURE, which is used for generating REST controllers and domain CLASSES (POJO) for the application. This helps in maintaining the API definition and code always in sync. |
|
| 20. |
Spring boot example to develop the Exception handler? |
|
Answer» Below code STRUCTURE represent the ControllerAdvice class developed using spring boot framework to handle the exception. import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; // Need to mention the RestController so that it will behave as a controller class @ControllerAdvice public class ProductExceptionController { // Below method USE to handle the exception, which is being generated by the RENT //endpoint method. This method also ACT as a User define exception. @ExceptionHandler(value = ProductNotfoundException.class) public ResponseEntity<Object> exception(ProductNotfoundException exception) { return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND); } }
|
|
| 21. |
Example of @DELETE rest endpoint? |
|
Answer» Below code structure represent the Rest Controller class developed using spring boot framework which use to ACT as Http Delete method. IMPORT java.util.Map; // Below series of import is important package specially org.springframework package import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.practise.springboot.Product // NEED to mention the RestController so that it will behave as rest end point. @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); // Below method responsible to handle the HTTP DELETE request, which will RECEIVE the Path //variable {id } as a parameter and responsible to delete the database information according // to the id parameter. @RequestMapping(value = "/PRODUCTS/{id}", method = RequestMethod.DELETE) public ResponseEntity<Object> delete(@PathVariable("id") String id) { productRepo.remove(id); return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK); } } |
|
| 22. |
Example of @PUT rest endpoint? |
|
Answer» Below code structure represent the Rest Controller class developed USING spring boot framework which USE to act as Http Put method. import java.util.HASHMAP; import java.util.Map; // Below series of import is important PACKAGE specially org.springframework package import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.practise.springboot.Product; // Need to mention the RestController so that it will behave as rest END point. @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); // Below method responsible to handle the HTTP PUT request, which will receive the Path //variable {id } as a parameter and responsible to update the database information according // to the id parameter. @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK); } } |
|
| 23. |
Example of @POST rest endpoint? |
|
Answer» Below code structure represent the Rest Controller CLASS developed using SPRING boot framework which use to act as HTTP POST method. import java.util.HashMap; import java.util.Map; // Below series of import is important package specially org.springframework package import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.practise.springboot.Product; // Need to mention the RestController so that it will behave as rest end point. @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); // Below method works as a POST method, which is responsible to receive the HTTP Post //method call along with RequestBody which has a product information, need to persist in //Database and will return the HTTP Status as CREATED. @RequestMapping(value = "/products", method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productRepo.post(product.getId(), product); return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED); } } } |
|
| 24. |
Example of @Get endpoint? |
|
Answer» Below code structure represent the Rest Controller class developed using spring boot FRAMEWORK which use to act as Http Get method. // Below series of import is important package specially org.springframework package. import java.util.HASHMAP; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.practise.springboot.model.Product; // Need to mention the RestController so that it will behave as rest end point. @RestController public class ProductServiceController { private static Map<String, Product> productRepo = NEW HashMap<>(); static { Product honey = new Product(); honey.setId("1"); honey.setName("Honey"); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId("2"); almond.setName("Almond"); productRepo.put(almond.getId(), almond); } // Below method act as a GET method, which is responsible to receive the HTTP GET call and return back the Product details as a RESPONSE along with the HTTP Status OK. @RequestMapping(value = "/products", method = RequestMethod.GET) public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } } |
|
| 25. |
How does the main method look like in Spring boot or code snippet of main method? |
|
Answer» Below code structure REPRESENT the main method of spring boot which use to kick start the spring boot application along with the configuration details which is in annotated form. import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /* Below code is sample code to run the spring boot application from main method. * We have to add the ComponentScan annotation to instantiate the bean for onfigure CLASS. * Need to add the EnableAuutoConfiguration to do auto configuraion according to the * *dependencies. * SpringBootApplication annotation responsible to make the class as a spring boot application. */ @ComponentScan @EnableAutoConfiguration @SpringBootApplication public class SpringBootApplication { public static void main(String[] ARGS) { // Below syntax use to run the spring boot application with internal CONFIGURE web server, //which publish deploy and publish the web services, once this PROCESS succcessful and web //seriver is up, the web service is available for the configure request. SpringApplication.run(SpringBootApplication.class, args); } }To run the above code, we have to run the below command either from command prompt or shell: mvn spring-boot: run |
|
| 26. |
What are the important annotations use to create the interceptor and what all their annotation does? |
|
Answer» INTERCEPTOR is one of the prominent features of spring boot and must use the @COMPONENT annotated class that supports it and it should implement the HandlerInterceptor interface. There are three methods which are USED to implement the interceptor.
|
|
| 27. |
How Spring boot application handle the runtime exception internally and what are the annotation to use to declare the user define exception? Any real time scenario where spring boot fit to handle the exception. |
|
Answer» Spring boot checks if any CLASS is annotated as @ControllerAdvice and @ExceptionHandler and called from rest end point layer, when any exception occurs than spring boot calls the corresponding annotated class to handle the error MESSAGE.
The real-time scenario is like, let’s say that most of the exception message is system generated and has a straightforward information, which is sometimes difficult to interpret by the user interface and understand by layman user, to solve this issue spring boot handle the error message and convert into the meaningful and comprehensive message which easy to understand and interpret. |
|
| 28. |
Explain how you will you go about Integration of Swagger with Spring |
|
Answer» Swagger is a set of open-source tools that helps with creating documentation for your REST services. <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.4.0</version> <scope>COMPILE</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.4.0</version> <scope>compile</scope> </dependencyThis is something you can ATTACH to your methods exposing REST endpoints. @Api @RestController public class MyController { @RequestMapping(method = RequestMethod.GET, path = "/welcome") @ApiOperation(value = "Welcome<Name> !!", NOTES = "returns welcome “) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 404, message = "Service not available"), @ApiResponse(code = 500, message = "Unexpected Runtime error") }) public String welcome(@RequestParam(value = "destination", defaultValue = "local") String CITY) { return "Welcome to an event @ " + city; } }To enable Swagger into your application , you will need the following configuration : @Configuration @EnableSwagger2 public class SwaggerConfig { public Docket helloApi() { return new Docket(DocumentationType.SWAGGER_2) .SELECT() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.ant("/welcome/*")) .build(); } }Start the application and to test the application, go to the following URL in the browser : http://localhost:8080/hello?name=John It should print “Welcome to an Event @ Singapore”. For checking the generated Swagger documentation, open this URL in the browser : http://localhost:8080/swagger-ui.html. |
|
| 29. |
Is it possible to have a Spring Boot Application without Spring Boot Starter Parent? If yes, when will you do that? |
|
Answer» In the majority of cases, you will build a Spring BOOT application using Spring Boot Starter Parent. However, there could be a case where you need to be very explicit about your dependencies and maven configuration. This could be a case of CORPORATE RULES or policies. In such cases, you may use scope=import to get the benefit of dependency MANAGEMENT intact. For example, <dependencyManagement> <dependencies> <dependency> <!-- Import dependency management from Spring Boot --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.6.release</version> <type>POM</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>Now include the required entries in dependencyManagement section before spring-boot-dependencies .For example, The next step is we need to add an entry in the dependencyManagement of your project before the spring-boot-dependencies entry. For example, you could add the following element to your pom.xml: <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-releasetrain</artifactId> <version>Fowler-SR2</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.1.0.BUILD-SNAPSHOT</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> |
|
| 30. |
Explain Spring Boot Starter Parent. |
|
Answer» When you generate a Spring Boot Project, you will see following inside your pom.xml file: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> </parent>This is reference to default Spring Boot Starter or parent Spring Boot Starter. You can use multiple child Projects using the configuration from this. This Starter gives you for free Configuration ( For example,Java Version) , Version of Dependencies ( Dependency MANAGEMENT) and default configuration for plugin. With parent Project, you get the following features :
Spring Boot Starter Parent has spring-boot-dependencies as the parent pom. It inherits dependency management from spring-boot-dependencies. <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.0.4.RELEASE</version> <relativePath>../../spring-boot-dependencies</relativePath> </parent>Minimum Java version is 8 with Spring 2. You Can configure the VARIOUS properties/configuration as under : <properties> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <resource.delimiter>@</resource.delimiter> <maven.compiler.source>1.8</maven.compiler.source> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.target>1.8</maven.compiler.target> </properties>Spring Boot Starter Parent specifies the default configuration for a host of plugins including maven-failsafe-plugin, maven-jar-plugin, maven-surefire-plugin, and maven-war-plugin ETC. |
|
| 31. |
Explain how you go about logging configuration in Spring Boot. |
|
Answer» You can use logging with SPRING Boot by specifying log levels on application.properties file. Spring Boot, by default, incorporates spring-boot-STARTER-logging as a transitive reliance for the spring-boot-starter MODULE. By default, Spring Boot incorporates SLF4J with Logback usage. Presently, if Logback is accessible, Spring Boot will pick it as the logging handler. You can undoubtedly arrange logging levels inside the application.properties document without making logging SUPPLIER explicit setup files, for example, logback.xml or log4j.properties. For example, the configuration is : logging.level.org.hibernate=ERROR logging.level.org.springframework.web=INFO If you would like to include Log4J or Log4j2, instead of Logback, you can exclude spring-boot-starter-logging and include the respective logging starter, as follows: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> </dependency>You will need to add log4j.properties file to the root classpath, Spring Boot will automatically pick it up. With log configuration, you may see the following THINGS:
|
|
| 32. |
Name & explain Common Boot Starters. |
Answer»
|
|
| 33. |
What is a Spring Boot Admin? How do you configure it? |
|
Answer» Spring Boot Admin is a web application that is used for Spring Boot applications management and monitoring. Each application is considered a client and registers to Spring Boot Admin Server. The Spring Boot Actuator endpoints give the magic behind the SCENES. <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server</artifactId> <version>2.1.6</version> </dependency> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server-ui</artifactId> <version>2.1.6</version> </dependency>With this, what you get for free is @EnableAdminServer, so let’s use this. @EnableAdminServer @SpringBootApplication PUBLIC class MySpringBootAdminApp { public static void main(String[] args) { SpringApplication.run(MySpringBootAdminApp.class, args); } }This sets up our admin server. Start the Admin Server and see if it is available at localhost:8080/admin/ Now, in your client application , we need a corresponding client which will register to this admin server. Use following in your client application. <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-client</artifactId> <version>2.1.6</version> </dependency>Now on the client SIDE, you also need to provide the url where admin server is running. Configure following in your client application’s application.properties: spring.boot.admin.url=http://localhost:8080 Spring Boot Admin can be configured to only show the data we deem helpful. We just need to change the default setup and add our own required metrics. For this configure following in application.properties of Spring Boot Admin Server. spring.boot.admin.routes.endpoints=env, metrics, trace, Jolokia, info, configprops |
|
| 34. |
What is AMQP? What does Spring Boot offer with respect to Messaging with AMQP? |
|
Answer» AMQP is a platform-independent protocol. Spring Boot provides Starter for AMQP spring-boot-starter-amqp. With this starter imported, if you have RabbitMQ running , Spring Boot will auto configure connection to RabbitMQ from your application. If you want to customize the configuration, you can use: spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=admin spring.rabbitmq.password=secret Additional Properties for Retry : spring.rabbitmq.template.retry.enabled=true spring.rabbitmq.template.retry.initial-interval=2s You can use AMQPTemplate or RabbitMessagingTemplate for sending messages similar to JMSTemplate. For receiving messages, you can use @RabbitListener(queue=”MyQueue”) @COMPONENT PUBLIC class SomeBean { @RabbitListener(destination=”somequeue”) public VOID processMessage(String content) { } }If you want to override DEFAULT Connection Factory, you can make use of SimpleRabbitListenerContainerFactoryConfigurer as follows : @Bean public SimpleRabbitListenerContainerFactory myFactory( SimpleRabbitListenerContainerFactoryConfigurer configurer) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); configurer.configure(factory, connectionFactory); factory.setMessageConverter(myMessageConverter()); return factory; }In this case , your listener will be changed to : @Component public class SomeBean { @RabbitListener(destination=”somequeue” containerFactory=”myAMQPFactory”) public void processMessage(String content) { } } |
|
| 35. |
What does Spring Boot offer with respect to Messaging using ConnectionFactory? |
|
Answer» Spring Boot offers a number of features with respect to Messaging. To start with let’s talk about javax.jms.ConnectionFactory. 1. Using ConnectionFactory This provides an Interface to send & receive MESSAGES. Spring uses JNDI to LOOK for the ConnectionFactory which you can configure by using the following property in APPLICATION.properties : spring.jms.jndi-name=java:/MyConnectionFactoryAlternatively, if ActiveMQ Starter is used, Spring Boot will autoconfigure the factory. You can customize the configuration using following properties : spring.activemq.broker-url=tcp://localhost:9876 spring.activemq.user=activeemq spring.activemq.password=password spring.activemq.pool.enabled=true spring.activemq.pool.max-connections=50 spring.jms.cache.session-cache-size=10How do you send & receive Messages? To send a message , you can inject org.springframework.jms.core.JmsTemplate into your application bean and use it for sending messages. For example, @COMPONENT public class MyMessageBean { private final JmsTemplate jmsTemplate; @Autowired public MyMessageBean(JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } }You can convert a simple method into Message Listener by using annotation org.springframework.jms.annotation.JMSListener (destination =”myQueue”) @Component public class SomeBean { @JmsListener(destination=”somequeue”) public void processMessage(String content) { } }To override default Connection Factory, you can make use of DefaultJmsListenerContainerFactoryConfigurer as follows: @Bean public DefaultJmsListenerContainerFactory myFactory( DefaultJmsListenerContainerFactoryConfigurer configurer) { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory, connectionFactory()); factory.setMessageConverter(myMessageConverter()); return factory; }Now your listener would be as follows : @Component public class SomeBean { @JmsListener(destination=”somequeue” containerFactory=”myFactory”) public void processMessage(String content) { } } |
|
| 36. |
How do you go about integrating Spring Boot with Hibernate? |
|
Answer» Hibernates gels well with Spring and with Spring Boot around, it makes the task super easy. We will see a generic way of Integrating Hibernate using Spring Boot in such a way that switching to some other jpa vendor tomorrow would be super easy. Let’s start with the process. 1. First thing first, you will need spring-boot-starter-data-jpa. Since Spring uses Hibernate as default vendor, you really don't need to configure or mention Hibernate explicitly somewhere. 2. Second step would be Drafting the ENTITY Class. Let’s consider, we are building an application to get a list of employees. So Employee, in this case, would be an Entity for us. You can use @javax.persistence.Entity annotation to DEFINE your entity as : @Entity public class Employee { @Id @GeneratedValue private Long id; private String name; //……./// Getters & Setters 3. Extend the JpaRepository and define methods ( if required). Your get all CRUD operations method inbuilt and if you need any additional customized methods, you can define them here. In our example, we don't need to define any method as a JPA repository does provide findAll() method. @Repository public interface EmployeeRepository extends JpaRepository<Employee, Long>{ } Actually, that’s it, you are DONE from an Integration point of view. Of course, you will need a few additional things from an OPERATIONAL point of view that we would define below. 4. Table Naming in Capitals : For this set following property in application.properties spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl 5. For Operational purpose in this example, we are using H2, so for that : a) INCLUDE H2 maven dependency in pom.xml <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency>b) Enable H2 by setting following property in application.properties spring.h2.console.enabled=true 6. Define EmployeeService : @Service public class EmployeeService { @Autowired private EmployeeRepository employeeRepository; public List<Employee> getAllEmployees() { return employeeRepository.findAll(); } }7. Include Spring-boot-web-starter in pom.xml abd Define EmployeeController : <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> @RestController @RequestMapping("/employees") public class EmployeeController { @Autowired private EmployeeService employeeService; @GetMapping public List<Employee> getAllEmployees() { return employeeService.getAllEmployees(); } }The Code is available in GitHub @ Now Start the application and hit http://localhost:8080/h2-console Change JDBC url to “jdbc:h2:mem:testdb”. Leave others with default values and login and execute the following queries : insert into EMPLOYEE values(1, ‘Virat’); insert into EMPLOYEE values(2, ‘Rohit’); insert into EMPLOYEE values(3, ‘Rahul’); Now hit the http://localhost:8080/employees endpoint and see the list of employees just entered. |
|
| 37. |
What is the difference between Spring Boot 1 & Spring Boot 2? |
Answer»
With Spring Boot2, everything is secured, actuator endpoints as well as static resources.
New Starters for Reactive components like MongoDB, Redis, Cassandra.
All endpoints are now under /actuator endpoint. You can tweak this path by using management.endpoints.web.base-path property. All are disabled by DEFAULT( except /health & /info) . To enable you can use management.endpoints.web.exposure.include=* ( or list endpoints to be enabled) You can easily write a new endpoint using @Endpoint annotation and it will get listed under /actuator. For example, @Component @Endpoint(id = "newapp") public class NewAppEndpoint { private Map<String, NewApp> newAppStore = new ConcurrentHashMap<>(); @ReadOperation public Map<String, NewApp> newApps() { return newAppStore; } @ReadOperation public NewApp newApp(@SELECTOR String name) { return newAppStore.get(name); } @WriteOperation public void configureNewApp(@Selector String name, NewApp newApp) { newAppStore.put(name, newApp); } @DeleteOperation public void deleteNewApp(@Selector String name) { newAppStore.remove(name); } public static class NewApp { private Boolean enabled; //Other properties & their Setter/Getters.. } }SIMILARLY, we can use @EndPointWebExtension to extend an existing endpoint.
|
|
| 38. |
How can you change output artefact of Spring Boot application from jar to WAR? |
Answer»
|
|
| 39. |
Explain the use of Spring Boot Maven plugin? |
|
Answer» Spring Boot eases QUICK starting a new feature from an application DEVELOPMENT POINT of view. However, what about building, packaging and other life CYCLE steps of your Spring Boot application. Here, Spring Boot maven plugin comes to your rescue. <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.1.6.RELEASE</version> <executions> <execution> <goals> <goal>REPACKAGE</goal> </goals> </execution> </executions> </plugin> </plugins> </build>It helps to collect all the jars on the classpath and builds a single, runnable jar ", which makes it more convenient to execute and transport your service. It searches for the public static void main() method to flag as a runnable class. The Spring Boot Plugin has the following goals.
|
|
| 40. |
Explain various @Conditional Annotations in Spring Boot. |
|
Answer» For Class level conditions, you can have @ConditionalOnClass and @ConditionalOnMissingClass. The @ConditionalOnClass and @ConditionalOnMissingClass annotations let @Configuration classes be included based on the presence or absence of specific classes. For example, using these conditions, Spring will only use configuration MyConfiguration bean if the SomeClass is present on the classpath: @Configuration @ConditionalOnClass(SomeClass.class) class MyConfiguration { //... }Similarly, in the following example, Spring will only use configuration MyConfiguration bean if the SomeClass is absent on classpath: @Configuration @ConditionalOnMissingClass(SomeClass.class) class MyConfiguration { //... }Similarly, there is something called, @ConditionalOnBean and @ConditionalOnMissingBean. If the beans specified as PART of this annotation are available on classpath then class will be considered for Configuration. @Bean @ConditionalOnBean(name = "dependentBean") Mybean myBean() { // ... }Here MyBean will be created only if dependentBean exists on classpath, this is very useful to create bean in ApplicationContext. @Configuration public class MyAutoConfiguration { @Bean @ConditionalOnMissingBean public MyService myService() { ... } }Here if myService bean will be created only if no existing my service bean exists in ApplicationContext. @ConditionalOnProperty This tells Spring to INCLUDE Configuration based on PROPERTY value. This can come to rescue for defining environment-specific beans. In the following example, the instance of MyBean will be created only if = local. @Bean @ConditionalOnProperty( name = "usemysql", havingValue = "local" ) MyBean myBean() { // ... }If you want to include configuration if a specific resource is present, then you can use @ConditionalOnResource is present. The @ConditionalOnResource annotation lets configuration be included only when a specific resource is present: @ConditionalOnResource(resources = "classpath:myproperties.properties") Properties myProperties() { // ... }Let’s consider a situation, where you WOULD LIKE to include a particular configuration only if the application is a web application. In such cases, you can use @ConditionalOnWebApplication annotation. @ConditionalOnWebApplication MyController myController() { // ... }Similarly, we have @ConditionalOnNotWebApplication which can be used to include configuration if the application is non-web application. We have seen various @Condition annotation which are for specific use cases. If we have a general and more complex requirement, we can make use of @Conditional annotation & @ConditionalExpression annotation. @Bean @ConditionalOnExpression("${isProduction} && ${myserver == weblogic}") DataSource dataSource() { // ... } |
|
| 41. |
What are different ways of running Spring Boot Application? |
|
Answer» Spring Boot OFFERS different ways of running an APPLICATION. These are : Running the Application as Spring Boot Application 1. Running the application in an external TomcatBy Packaging the application as War application and deploying it to an external Tomcat WEB server. 2. Running the application using java -jar “artifcat_name”.java -jar target/mydemoapp.jar To Support remote debugging for this, you can use the following parameters along with the java command : java -Xdebug -Xrunjdwp:server=y, transport=dt_socket, address=8000,suspend=n \ -jar target/mydemoapp.jar 3. By using Maven or GRADLE Pluginmvn spring-boot:run You can use the MAVEN_OPTS environment variable export MAVEN_OPTS=-Xmx1024m gradle bootRun You can use JAVA_OPTS environment variable export JAVA_OPTS=-Xmx1024m |
|
| 42. |
How can you do the Integration Test with Spring Boot? |
|
Answer» You can use @SpringBootTest annotation. This is over and above the spring-test module. When you include @SpringBootTest, applicationContext is started. @RunWith(SpringRunner.class) @SpringBootTest public class YourTestClass {SpringBootTest supports different modes, you can enable anyone of them by using web environment property along with @SpringBootTest. These modes are :
These TWO modes are important from an Integration point of view, other modes supported are :
For example, if you go for RANDOM_PORT, code will look LIKE : @RunWith(SpringRunner.class) @SpringBootTest(web environment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class YourTestClass @MockBean : You can make use of @MockBean to mock a particular service or repository or some bean. For example, RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class YourTestClass { @MockBean private EmployeeRepository employeeRepository; @Autowired private EmployeeService employeeService; @Test public void testRetrieveStudentWithMockRepository() throws Exception { Optional<Employee> employee = Optional.of( new Employee(1,"Scott")); when(employeeRepository.findById(49)).thenReturn(employee); assertTrue(employeeService.retrieveStudent(49).getName().contains("Scott")); } }Using MockMvc & @AutoConfigureMockMvc: You can mock up the http requests using MockMvc & @AutoConfigureMockMvc For example, @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class YourTestClass { @Autowired private MockMvc mockMvc; @Test public void testMethod() throws Exception { this.mockMvc.perform(post("/employees")).andExpect(status().is2xxSuccessful()); this.mockMvc.perform(get("/employee/49")).andDo(print()).andExpect(status().isOk()) .andExpect(content().string(containsString("Rahul"))); } } |
|
| 43. |
What is Spring Application Properties and how it is used? |
|
Answer» Spring Boot LETS us define Application Properties to support us for work in different environments. These properties include parameters like application name, server port number, data source details, PROFILES, and many other useful properties. Spring Boot supports YAML based properties configurations to RUN the application. We can simply put an “application.yml” file in “src/main/resources” directory, and it will be auto-detected. So, by using this default file, we don’t NEED to explicitly register a PropertySource, or provide a PATH to a property file, unlike native Spring where we have explicitly define them. A sample application.yml file looks like below: spring: application: name: SampleRestService profiles: active: prod server.port = 9090 |
|
| 44. |
What is Spring Boot DevTools? |
|
Answer» Spring Boot provides ‘spring-boot-devtools’ module with features that help the programmers while developing the application. It basically improves the experience of developing a Spring Boot application. One of the key features is AUTOMATIC reload of application as soon as there is a change; hence developer does not NEED to STOP and start the application each time. The is an intelligent feature as it only reloads the actively developed classes but not the third-party JARs. Another key feature is that by def,ault it disables the caching of view templates and static files. This enables a developer to see the changes as soon as they make them. In CASE, we want to DISABLE any of these features, then we need to set them in an application.yml file. For example -Dspring.devtools.restart.enabled=false will avoid automatic application restart. Below are a few of the features provided:
|
|
| 45. |
What is Aspect Orientated Programming? |
|
Answer» Aspect Orientated Programming (AOP) is a mechanism for adding certain behavior by virtually breaking the program logic into distinct parts called concerns. This helps in increasing modularity by cross-cutting the concerns. These cross-cutting concerns SPAN across multiple points of an application and are conceptually separate from the application's BUSINESS logic. For e.g. transaction management, authentication, logging, security, etc. It is a concept in contrast to OBJECT Oriented Programming (OOPS) and Dependency Injection (DI). The key unit of modularity in OOPS is the class, whereas in AOP the unit of modularity is the aspect. DI allows the application to decouple the objects from each other and AOP helps to decouple cross-cutting concerns from the objects that they affect. Spring AOP module provides interceptors to intercept an application. For example, when a method is executed, we can add custom functionality before or after the method is executed. Below are few important AOP concepts: |
|
| 46. |
Can you create a custom Spring Boot starter? |
|
Answer» Yes, we can create our own custom starters. For instance, if we have an internal LIBRARY for USE within the organization which is used ACROSS multiple PROJECTS. Then it would be a good practice to create a starter for it and to be used in Spring Boot CONTEXT. These starters enable developers to avoid lengthy configuration and quickly jumpstart their development by the use of simple annotations. To create our own custom starter, we require to create an auto-configuration class with an auto-configure module and a starter module which will bring all required dependencies using pom.xml or build.gradle. Spring Boot custom starter have certain guidelines for the naming convention. They should not start with Spring Boot and ideally, have a name like “name-spring-boot-starter”. |
|
| 47. |
Explain the Database/Repository annotations used in Spring? |
|
Answer» Below are the significant annotations used for connecting a database with Spring application:
|
|
| 48. |
How do you implement Exception Handling in Spring Boot? |
|
Answer» The IDEAL approach to implement Exception Handling in Spring Boot is by using @ControllerAdvice annotation. It ALLOWS the multiple scattered @ExceptionHandler to be consolidated into a single global error handling component. It allows full control over the body of the response as well as the status code by use of ResponseEntity. It allows to handle and define the behavior of SEVERAL exceptions in the same class so that there is a common source of all application errors. It also allows to map different errors to the same method if desired. @ExceptionHandler annotation provides a mechanism for handling and defining behavior for the exceptions thrown during the execution of handlers (Controller OPERATIONS). @ResponseStatus is used to mark a method or exception with error status code and reason that should be returned to the client. The status code is applied to the HTTP response when the handler method is invoked, or whenever said the exception is thrown. Example: ControllerAdvice PUBLIC class ErrorHandler { @ExceptionHandler(GenericContractException.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public ResponseEntity<ContractError> handleGenericContractException( final GenericContractException ex) { LOGGER.error("Generic Contract Exception has occurred."); ContractError cerr = ex.createContractError(); return status(gcex.getRespCode()).body(cerr); } |
|
| 49. |
What is an Actuator? |
|
Answer» Spring Boot Actuator provides the ability to inspect the internals of an application at runtime. It provides application data on auditing, metrics, bean details, version details, CONFIGURATIONS, logger details via REST (HTTP) endpoints. These endpoints help in monitoring and managing a Spring Boot application in production. We can also add custom endpoints apart from the default 16 provided. HOWEVER, it should not be considered as a replacement for production-grade monitoring solutions though it provides a great starting point. The Actuator endpoint acts as a root for all other endpoints: http://localhost:8080/application Below are a few of the significant endpoints exposed:
This endpoint provides information about the operating SYSTEM, JVM, installation, system environment variables, and the values configured in application properties files. http://localhost:8080/application/env
This service provides details of the disk SPACE and status of the application. http://localhost:8080/application/health
This endpoint provides the details about all the beans that are loaded into the Spring context. It provides details like name, scope, type, location, and dependencies of the Bean. http://localhost:8080/application/beans
This endpoint shows metrics about Server memory, processors; JVM details like a heap, threads, garbage collection, etc. http://localhost:8080/application/metrics
Below actuator endpoints are exposed for debugging application: /application/heapdump: Provides a heap dump /application/trace: Provides a trace of the last few REQUESTS serviced by the application /application/dump: Provides a thread dump |
|
| 50. |
Which Annotation do you use to enable Spring Boot? Elaborate? |
|
Answer» @SpringBootApplication is the primary annotation which needs to be added to the Application class or the MAIN class to the project and enables features like JAVA-BASED Spring configuration, component scanning, and auto-configuration. An Application class is used to BOOTSTRAP and launch a Spring application from a Java main method. This class automatically creates the ApplicationContext from the classpath, scan the configuration classes and launch the application. @SpringBootApplication is essentially a combination of below annotations:
Following parameters are accepted in the @SpringBootApplication annotation:
Example: package com.example.demoApplication; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(exclude = { SecurityConfiguration.class }) public class Application { public static VOID main(String[] args) { SpringApplication.run(Application.class, args); } } |
|