Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the spectra-pro domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home4/mahidhar/public_html/wp-includes/functions.php on line 6114
Spring Framework - Top 25 Interview Questions | tutorialQ

Spring Framework – Top 25 Interview Questions

Here are the top 25 interview questions for the Spring Framework and Spring Boot, complete with detailed answers and relevant examples.

1. What is the Spring Framework?

Answer:
The Spring Framework is a comprehensive framework for enterprise Java development. It provides support for developing Java applications, facilitating dependency injection, aspect-oriented programming, transaction management, and more. Spring’s core features can be used by any Java application, although there are many extensions for building web applications on top of the Java EE (Enterprise Edition) platform.

2. What are the main features of the Spring Framework?

Answer:
The main features of the Spring Framework include:

  • Inversion of Control (IoC): Managing object dependencies through Dependency Injection (DI).
  • Aspect-Oriented Programming (AOP): Separating cross-cutting concerns from business logic.
  • Transaction Management: Providing a consistent approach to transaction management.
  • Data Access: Simplified access to relational databases using JDBC and object-relational mapping tools.
  • Model-View-Controller (MVC): Building web applications using a clear separation of concerns.
  • Security: Providing comprehensive security services for Java applications.

3. What is Dependency Injection (DI) in Spring?

Answer:
Dependency Injection (DI) is a design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at runtime or compile-time. DI is a form of Inversion of Control (IoC). In Spring, it allows for injecting dependencies through constructor, setter, or field injection.

// Constructor Injection
@Component
public class MyService {
    private final MyRepository repository;

    @Autowired
    public MyService(MyRepository repository) {
        this.repository = repository;
    }
}

// Setter Injection
@Component
public class MyService {
    private MyRepository repository;

    @Autowired
    public void setRepository(MyRepository repository) {
        this.repository = repository;
    }
}

// Field Injection
@Component
public class MyService {
    @Autowired
    private MyRepository repository;
}

4. What are the different types of dependency injection in Spring?

Answer:
The different types of dependency injection in Spring are:

  • Constructor Injection: Dependencies are provided through a class constructor.
  • Setter Injection: Dependencies are provided through setter methods.
  • Field Injection: Dependencies are injected directly into fields (using @Autowired).

5. What is the Spring IoC container?

Answer:
The Spring IoC (Inversion of Control) container is responsible for managing the lifecycle and configuration of application objects. It uses dependency injection to manage components and their dependencies. The container can be configured using XML, Java annotations, or Java code.

6. How do you configure Spring using XML?

Answer:
Spring configuration using XML involves defining beans and their dependencies in an XML file.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="myService" class="com.example.MyService">
        <property name="repository" ref="myRepository"/>
    </bean>

    <bean id="myRepository" class="com.example.MyRepository"/>
</beans>

7. How do you configure Spring using Java annotations?

Answer:
Spring configuration using Java annotations involves using annotations like @Component, @Autowired, @Configuration, @Bean, etc.

@Component
public class MyRepository {
    // ...
}

@Component
public class MyService {
    private final MyRepository repository;

    @Autowired
    public MyService(MyRepository repository) {
        this.repository = repository;
    }
}

@Configuration
public class AppConfig {
    @Bean
    public MyService myService(MyRepository myRepository) {
        return new MyService(myRepository);
    }
}

8. What is Spring Boot?

Answer:
Spring Boot is an extension of the Spring Framework that simplifies the setup, development, and deployment of Spring applications. It provides a set of pre-configured starter templates, reduces boilerplate code, and allows for convention-over-configuration.

9. What are the main features of Spring Boot?

Answer:
Main features of Spring Boot include:

  • Auto-Configuration: Automatically configures Spring applications based on the dependencies present in the project.
  • Starter POMs: Simplifies dependency management by providing a set of convenient dependency descriptors.
  • Spring Boot CLI: Allows for rapid application development with Groovy.
  • Embedded Servers: Supports embedded servers like Tomcat, Jetty, and Undertow, which eliminates the need for deploying WAR files.
  • Production-ready Features: Provides metrics, health checks, and externalized configuration.

10. How do you create a Spring Boot application?

Answer:
To create a Spring Boot application, you can use the Spring Initializr to generate the project structure and dependencies.

  1. Visit Spring Initializr.
  2. Choose project metadata (Maven/Gradle, language, Spring Boot version).
  3. Add dependencies (e.g., Spring Web, Spring Data JPA).
  4. Generate and download the project.
  5. Import the project into your IDE.
  6. Create a main application class with @SpringBootApplication annotation.
@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }
}

11. What is @SpringBootApplication?

Answer:
@SpringBootApplication is a convenience annotation that combines three annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan.

  • @Configuration: Indicates that the class provides Spring configuration.
  • @EnableAutoConfiguration: Enables Spring Boot’s auto-configuration mechanism.
  • @ComponentScan: Scans for Spring components in the specified package.

12. How do you define a Spring Boot application’s properties?

Answer:
Spring Boot applications are configured using properties defined in application.properties or application.yml files, which are typically located in the src/main/resources directory.

# application.properties
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
# application.yml
server:
  port: 8081
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: secret

13. What is Spring Data JPA?

Answer:
Spring Data JPA is a part of the Spring Data project that makes it easier to implement JPA-based repositories. It reduces boilerplate code by providing a set of interfaces and classes for database operations.

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String position;
    // Getters and setters
}

public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    List<Employee> findByPosition(String position);
}

14. How do you handle exceptions in Spring Boot?

Answer:
In Spring Boot, you can handle exceptions using @ControllerAdvice and @ExceptionHandler annotations.

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGeneralException(Exception ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

15. What is the use of @RestController in Spring Boot?

Answer:
@RestController is a convenience annotation that combines @Controller and @ResponseBody. It is used to create RESTful web services in Spring Boot.

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
    private final EmployeeRepository repository;

    @Autowired
    public EmployeeController(EmployeeRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/{id}")
    public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id) {
        return repository.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee) {
        return ResponseEntity.status(HttpStatus.CREATED).body(repository.save(employee));
    }
}

16. How do you secure a Spring Boot application?

Answer:
You can secure a Spring Boot application using Spring Security. Add the dependency to your pom.xml or build.gradle file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Then configure security settings:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            .and()
            .formLogin().permitAll()
            .and()
            .logout().permitAll().permitAll();
    }
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception  
    {
        auth.inMemoryAuthentication()
            .withUser("user").password("{noop}password").roles("USER")
            .and()
            .withUser("admin").password("{noop}admin").roles("ADMIN");
    }
}

Certainly! Here are the remaining 9 questions and answers for Spring Boot, starting from the 17th question:

17. How do you create a custom Spring Boot starter?

Answer:
To create a custom Spring Boot starter, follow these steps:

  1. Create a new project: Set up a new Maven or Gradle project.
  2. Add dependencies: Include dependencies that your starter will manage.
  3. Auto-configuration: Create an auto-configuration class annotated with @Configuration and @ConditionalOnClass to conditionally configure beans.
  4. META-INF/spring.factories: Create a spring.factories file in the META-INF directory to register your auto-configuration class.
@Configuration
@ConditionalOnClass(SomeLibrary.class)
public class CustomStarterAutoConfiguration {
    @Bean
    public SomeService someService() {
        return new SomeService();
    }
}
# META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.example.CustomStarterAutoConfiguration

18. What are Spring Profiles and how do you use them?

Answer:
Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments. Profiles are specified in configuration files (application-{profile}.properties) and activated by setting the spring.profiles.active property.

# application-dev.properties
spring.datasource.url=jdbc:h2:mem:devdb

# application-prod.properties
spring.datasource.url=jdbc:mysql://prod-db-server/proddb
@Profile("dev")
@Bean
public DataSource devDataSource() {
    return new H2DataSource();
}

@Profile("prod")
@Bean
public DataSource prodDataSource() {
    return new MySQLDataSource();
}

Activate a profile by setting the spring.profiles.active property:

spring.profiles.active=dev

19. How do you enable and configure Spring Boot Actuator?

Answer:
Spring Boot Actuator provides endpoints to monitor and manage your application. To enable Actuator, add the dependency to your pom.xml or build.gradle file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Configure Actuator endpoints in application.properties:

management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.show-details=always

Access Actuator endpoints, such as /actuator/health and /actuator/info.

20. How do you handle exceptions globally in Spring Boot?

Answer:
Global exception handling in Spring Boot can be achieved using @ControllerAdvice and @ExceptionHandler annotations:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGeneralException(Exception ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

21. What is Spring Boot DevTools and how does it help during development?

Answer:
Spring Boot DevTools is a module that provides features to aid development, such as automatic restarts, live reload, and configurations for faster feedback. To use DevTools, add the dependency to your pom.xml or build.gradle file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
</dependency>

Features include:

  • Automatic Restart: Restarts the application whenever classpath changes.
  • Live Reload: Refreshes the browser automatically when resources change.
  • Property Defaults: Disables caching for templates and static resources.

22. How do you configure a Spring Boot application to connect to a database?

Answer:
To configure a Spring Boot application to connect to a database, follow these steps:

  1. Add database dependencies: Include the appropriate JDBC driver and Spring Data JPA starter in your pom.xml or build.gradle file.
  2. Configure database properties: Define database connection properties in application.properties.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
  1. Create entity and repository: Define JPA entities and Spring Data repositories.
@Entity
public class User {
    @Id @GeneratedValue
    private Long id;
    private String name;
    // getters and setters
}

public interface UserRepository extends JpaRepository<User, Long> {
}

23. How do you secure a Spring Boot application using Spring Security?

Answer:
To secure a Spring Boot application using Spring Security:

  1. Add Spring Security dependency: Include the Spring Security starter in your pom.xml or build.gradle file.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
  1. Create a security configuration class: Define a configuration class to customize security settings.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            .and()
            .formLogin().permitAll()
            .and()
            .logout().permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("{noop}password").roles("USER")
            .and()
            .withUser("admin").password("{noop}admin").roles("ADMIN");
    }
}

24. How do you deploy a Spring Boot application to a cloud platform like AWS?

Answer:
To deploy a Spring Boot application to AWS, you can use Elastic Beanstalk, EC2, or ECS. Here’s an example of deploying using Elastic Beanstalk:

  1. Create a deployment package: Package your application as a JAR or WAR file.
  2. Create an Elastic Beanstalk application: Use the AWS Management Console or AWS CLI to create an application and environment.
  3. Deploy the application: Upload the deployment package through the AWS Management Console or use the AWS CLI.
aws elasticbeanstalk create-application --application-name my-app
aws elasticbeanstalk create-environment --application-name my-app --environment-name my-env --solution-stack-name "64bit Amazon Linux 2 v3.1.6 running Corretto 11"
aws elasticbeanstalk create-application-version --application-name my-app --version-label v1 --source-bundle S3Bucket="my-bucket",S3Key="my-app.jar"
aws elasticbeanstalk update-environment --environment-name my-env --version-label v1

25. How do you configure logging in a Spring Boot application?

Answer:
Spring Boot uses SLF4J as a logging facade and supports various logging frameworks like Logback, Log4j2, and Java Util Logging. To configure logging:

  1. Add logging dependencies (if needed): Include the desired logging framework in your pom.xml or build.gradle file.
  2. Configure logging properties: Define logging configurations in application.properties or use a custom configuration file (e.g., logback-spring.xml for Logback).
# application.properties
logging.level.org.springframework=INFO
logging.level.com.example=DEBUG
logging.file.name=app.log
<!-- logback-spring.xml -->
<configuration>
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/app.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>logs/app.%d{yyyy-MM-dd}.log</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="FILE"/>
    </root>
</configuration>

These questions and answers provide a comprehensive overview of Spring Boot, covering topics such as custom starters, profiles, Actuator, exception handling, DevTools, database connectivity, security, cloud deployment, and logging.

Scroll to Top