Spring Boot Interview Questions - BEHIND JAVA

Spring Boot Interview Questions

Share This

How to connect multiple datasources with Spring Boot and Spring Data?

1. Add an additional datasource configuration to your application.properties

2. Set the SQL Dialect to “default” in your application.properties to let Spring autodetect the different SQL Dialects of each datasource

spring.jpa.database=default

3. Create a Java Package for each datasource with two nested Packages “domain” and “repo”

4. Create a Configuration Class for the Oracle database “foo” named “FooDbConfig.java”

Create a Configuration Class for the PostgreSQL database “bar” named “BarDbConfig.java”

6. Create an Entity “Foo.java” for the Oracle database “foo”

7. Create a Repository “FooRepository.java” for the Oracle database “foo”

9. Create a Repository “BarRepository.java” for the PostgreSQL database “bar”

11. Use the Repositories in a REST Controller (or somewhere else)

Difference between @Component vs @Repository vs @Controller and @Service in Spring?

@Component

We can use @Component across the application to mark the beans as Spring’s managed components. Spring only pick up and registers beans with @Component and doesn’t look for @Service and @Repository in general.

They are registered in ApplicationContext because they themselves are annotated with @Component

@Component
public @interface Service {
}

@Component
public @interface Repository {
}

@Service and @Repository are special cases of @Component. They are technically the same but we use them for the different purposes.

@Repository Annotation

Although above use of @Component is good enough but we can use more suitable annotation that provides additional benefits specifically for DAOs i.e. @Repository annotation. The @Repository annotation is a specialization of the @Component annotation with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.

@Service Annotation

The @Service annotation is also a specialization of the component annotation. It doesn’t currently provide any additional behavior over the @Component annotation, but it’s a good idea to use @Service over @Component in service-layer classes because it specifies intent better. Additionally, tool support and additional behavior might rely on it in the future.

@Controller Annotation

@Controller annotation marks a class as a Spring Web MVC controller. It too is a @Component specialization, so beans marked with it are automatically imported into the DI container. When we add the @Controller annotation to a class, we can use another annotation i.e. @RequestMapping; to map URLs to instance methods of a class.

What is the Use of Spring @Required Annotation?

In a production-scale application, there may be hundreds or thousands of beans declared in the IoC container, and the dependencies between them are often very complicated. One of the shortcomings of setter injection is that it’s very hard for you to check if all required properties have been set or not. Using “dependency-check” attribute of you can check if attributes values have been set but it can’t check if their value is set to null or non-null values.

Apart from verifying dependencies using dependency-check, you can use @Required annotation to check if values set are non-null.

1) Use @Required annotation over setter methods

Use the @Required annotation over setter method of bean property in class file as below:

2) Register RequiredAnnotationBeanPostProcessor class

RequiredAnnotationBeanPostProcessor is a spring bean post processor that checks if all the bean properties with the @Required annotation have been set. To enable this bean post processor for property checking, you must register it in the Spring IoC container.

applicationContext.xml

If any property with @Required have not been set, a BeanInitializationException will be thrown by this bean post processor. For example, if I will create an instance of EmployeeFactoryBean class without passing property value for designation, then I will get this error.

What is the use of @Scheduled Annotation?

@Scheduled annotation is used for task scheduling. The trigger information needs to be provided along with this annotation. You can use the properties fixedDelay/fixedRate/cron to provide the triggering information. where –

  • fixedRate makes Spring run the task on periodic intervals even if the last invocation may be still running.
  • fixedDelay specifically controls the next execution time when the last execution finishes.
  • cron is a feature originating from Unix cron utility and has various options based on your requirements.

Example usage can be as below:

@Scheduled(fixedDelay =30000)
public void demoServiceMethod () {... }
 
@Scheduled(fixedRate=30000)
public void demoServiceMethod () {... }
 
@Scheduled(cron="0 0 * * * *")
public void demoServiceMethod () {... }

What is a Spring Boot Interceptor?

You can use the Interceptor in Spring Boot to perform operations under the following situations −

  • Before sending the request to the controller
  • Before sending the response to the client

For example, you can use an interceptor to add the request header before sending the request to the controller and add the response header before sending the response to the client.

To work with interceptor, you need to create @Component class that supports it and it should implement the HandlerInterceptor interface.

The following are the three methods you should know about while working on Interceptors −

  • preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client.
  • postHandle() method − This is used to perform operations before sending the response to the client.
  • afterCompletion() method − This is used to perform operations after completing the request and response.

Observe the following code for a better understanding −

You will have to register this Interceptor with InterceptorRegistry by using WebMvcConfigurerAdapter as shown below

How to create Unit Test for REST Controller?

First, we need to create Abstract class file used to create web application context by using MockMvc and define the mapToJson() and mapFromJson() methods to convert the Java object into JSON string and convert the JSON string into Java object.

Next, write a class file that extends the AbstractTest class and write a Unit Test for each method such GET, POST, PUT and DELETE.

The code for GET API Test case is given below. This API is to view the list of products.

@Test
public void getProductsList() throws Exception {
   String uri = "/products";
   MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri)
      .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();
   
   int status = mvcResult.getResponse().getStatus();
   assertEquals(200, status);
   String content = mvcResult.getResponse().getContentAsString();
   Product[] productlist = super.mapFromJson(content, Product[].class);
   assertTrue(productlist.length > 0);
}

How to configure HTTPS on spring boot?

Self-Signed Certificate

To create a self-signed certificate, Java Run Time environment comes bundled with certificate management utility key tool. This utility tool is used to create a Self-Signed certificate. It is shown in the code given here

keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650
Enter keystore password:
   Re-enter new password:
   What is your first and last name?
   [Unknown]:
   What is the name of your organizational unit?
   [Unknown]:
   What is the name of your organization?
   [Unknown]:
   What is the name of your City or Locality?
   [Unknown]:
   What is the name of your State or Province?
   [Unknown]:
   What is the two-letter country code for this unit?
   [Unknown]:
   Is CN = Unknown, OU=Unknown, O = Unknown, L = Unknown, ST = Unknown, C = Unknown correct?
   [no]: yes
   

This code will generate a PKCS12 keystore file named as keystore.p12 and the certificate alias name is tomcat.

Configure HTTPS

We need to provide the server port as 443, key-store file path, key-store-password, key-store-type and key alias name into the application.properties file. Observe the code given here

server.port: 443
server.ssl.key-store: keystore.p12
server.ssl.key-store-password: springboot
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat

How to enable CORS support in spring boot?

Cross-Origin Resource Sharing (CORS) is a security concept that allows restricting the resources implemented in web browsers. It prevents the JavaScript code producing or consuming the requests against different origin.

For example, your web application is running on 8080 port and by using JavaScript you are trying to consuming RESTful web services from 9090 port. Under such situations, you will face the Cross-Origin Resource Sharing security issue on your web browsers.

Two requirements are needed to handle this issue −

  • RESTful web services should support the Cross-Origin Resource Sharing.
  • RESTful web service application should allow accessing the API(s) from the 8080 port.

In this chapter, we are going to learn in detail about How to Enable Cross-Origin Requests for a RESTful Web Service application.

Enable CORS in Controller Method

We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.

Global CORS Configuration

We need to define the shown @Bean configuration to set the CORS configuration support globally to your Spring Boot application.

How to enable Internationalization spring boot?

Internationalization is a process that makes your application adaptable to different languages and regions without engineering changes on the source code. In either words, Internationalization is a readiness of Localization.

We need to determine default Locale of your application. We need to add the LocaleResolver bean in our Spring Boot application.

@Bean
public LocaleResolver localeResolver() {
   SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
   sessionLocaleResolver.setDefaultLocale(Locale.US);
   return sessionLocaleResolver;
   }
   

LocaleChangeInterceptor

LocaleChangeInterceptor is a used to change the new Locale based on the value of the language parameter added to a request.

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
   LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
   localeChangeInterceptor.setParamName("language");
   return localeChangeInterceptor;
}

To take this effect, we need to add the LocaleChangeInterceptor into the application’s registry interceptor. The configuration class should extend the WebMvcConfigurerAdapter class and override the addInterceptors() method.

@Override
public void addInterceptors(InterceptorRegistry registry) {
   registry.addInterceptor(localeChangeInterceptor());
}

Messages Sources

Spring Boot application by default takes the message sources from src/main/resources folder under the classpath. The default locale message file name should be message.properties and files for each locale should name as messages_XX.properties. The “XX” represents the locale code.

All the message properties should be used as key pair values. If any properties are not found on the locale, the application uses the default property from messages.properties file.

The default messages.properties will be as shown −

welcome.text=Hi Welcome to Everyone

The French language messages_fr.properties will be as shown −

welcome.text=Salut Bienvenue à tous

HTML file

In the HTML file, use the syntax #{key} to display the messages from the properties file.

<h1 th:text = "#{welcome.text}"></h1>

How to enable OAuth2 Sign-In?

write a Configuration file to enable the OAuth2SSO for web security and remove the authentication for index.html file as shown −

What is Hystrix? and how to enable Hystrix Spring Boot?

Hystrix is a library developed by Netflix and is part of Spring via the Spring Cloud Netflix project. Hystrix is a fault tolerance library and is used as strategy against failures (at different levels) in a service-layer.

Hystrix can be used in situations where your application depends on remote services. In case one or more remote services are down you can handle the situation by using a circuit breaker in your application.

Hystrix is watching methods for failing calls to related services. If there is such a failing method, it will open the circuit, which means, it forwards the call to a fallback method. In case the services is restored it will close the circuit and the applications acts as expected again.

For example, when you are calling a 3rd party application, it takes more time to send the response. So at that time, the control goes to the fallback method and returns the custom response to your application.

In this chapter you are going to see How to implement the Hystrix in a Spring Boot application.

First, we need to add the Spring Cloud Starter Hystrix dependency in our build configuration file.

Then add the @EnableHystrix annotation into your main Spring Boot application class file. The @EnableHystrix annotation is used to enable the Hystrix functionalities into your Spring Boot application.

The main Spring Boot application class file code is given below −

Now write a simple Rest Controller such that it returns the String after 3 seconds from the requested time.

Now, add the @Hystrix command and @HystrixProperty for the Rest API and define the timeout in milliseconds value.

@HystrixCommand(fallbackMethod = "fallback_hello", commandProperties = {
   @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
})

Next, define the fallback method fallback_hello() if the request takes a long time to respond.

private String fallback_hello() {
   return "Request fails. It takes long time to response";
}

The complete Rest Controller class file that contains REST API and Hystrix properties is shown here −

How to create war file from spring boot?

  • You need to extend SpringBootServletInitializer in your @SpringBootApplication
  • You don't need to add the spring-boot-starter-tomcat dependency for war file generation
  • Also use below configuration in pom.xml war

1 comment:

Pages