Spring Boot

Welcome to the Spring Boot & Microservices Interview Guide. Spring Boot is the most popular framework for Java enterprise applications. These questions cover everything from Auto-configuration to Spring Security and Cloud Native development.

Your Learning Progress 0% Completed

Started

Q1: What is @SpringBootApplication annotation? Easy +
It is a convenience annotation that combines three other annotations:
  • @Configuration: Tags the class as a source of bean definitions.
  • @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings.
  • @ComponentScan: Tells Spring to look for other components, configurations, and services in the package.
Q2: How does Spring Boot Auto-Configuration work? Hard +
Spring Boot looks at the dependencies on the classpath. If it finds h2.jar, it automatically configures an in-memory database. If it finds spring-webmvc, it sets up the DispatcherServlet.

This logic is handled by @EnableAutoConfiguration and the META-INF/spring.factories file.
// Example: Conditional configuration
@Configuration
@ConditionalOnClass(DataSource.class)
public class DatabaseAutoConfiguration {
    // Logic to setup DB automatically
}
Q3: What is difference between @Transactional at class level and method level? Hard +
@Transactional at Class Level:
  • Applies transaction management to all public methods of the class.
  • Acts as a default configuration for every method.
  • Reduces code duplication when most methods need transactions.
@Transactional at Method Level:
  • Applies transaction only to the specific method.
  • Provides fine-grained control over transaction settings.
  • Can override class-level transaction configuration.
Key Difference:
  • Class-level = default for all methods.
  • Method-level = specific control and override.
Example:
@Transactional
public class UserService {

    public void saveUser() {
        // Uses class-level transaction
    }

    @Transactional(readOnly = true)
    public User getUser() {
        // Overrides class-level with readOnly
    }
}
    
Q4: How do you configure multiple datasource in Spring Boot? Hard +
Multiple DataSource Configuration:
  • Used when application connects to more than one database.
  • Each datasource requires its own configuration, EntityManager, and TransactionManager.
  • One datasource should be marked as @Primary.
Step 1: application.properties
spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1
spring.datasource.primary.username=root
spring.datasource.primary.password=pass

spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2
spring.datasource.secondary.username=root
spring.datasource.secondary.password=pass
    
Step 2: Primary DataSource Config
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    basePackages = "com.example.repo.primary",
    entityManagerFactoryRef = "primaryEntityManagerFactory",
    transactionManagerRef = "primaryTransactionManager"
)
public class PrimaryDataSourceConfig {

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}
    
Step 3: Secondary DataSource Config
@Configuration
@EnableJpaRepositories(
    basePackages = "com.example.repo.secondary",
    entityManagerFactoryRef = "secondaryEntityManagerFactory",
    transactionManagerRef = "secondaryTransactionManager"
)
public class SecondaryDataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}
    
Key Points:
  • Use @EnableJpaRepositories to separate repositories.
  • Configure EntityManagerFactory and TransactionManager for each datasource.
  • Use @Primary to define default datasource.
Q5: What is difference between @RequestParam and @PathVariable? Easy +
@RequestParam:
  • Used to get values from query parameters in URL.
  • Parameters are passed after ? in key-value format.
  • Mostly used for optional or filtering data.
Example:
@GetMapping("/users")
public String getUser(@RequestParam String name) {
    return name;
}
// URL: /users?name=John
    
@PathVariable:
  • Used to extract values from URL path.
  • Value is part of the endpoint itself.
  • Mostly used for mandatory identifiers like ID.
Example:
@GetMapping("/users/{id}")
public String getUserById(@PathVariable int id) {
    return "User ID: " + id;
}
// URL: /users/101
    
Key Difference:
  • @RequestParam → Query parameter (?key=value)
  • @PathVariable → URL path (/value)
Q7: How do you monitor and optimize a Spring Boot application in production? Hard +
Monitoring:
  • Use Spring Boot Actuator to expose production-ready endpoints.
  • Monitor /health, /metrics, /loggers, /threaddump.
  • Integrate with tools like Prometheus and Grafana for visualization.
  • Use centralized logging (ELK stack - Elasticsearch, Logstash, Kibana).
Enable Actuator:
management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.show-details=always
    
Optimization Techniques:
  • Database Optimization: Use connection pooling (HikariCP), indexing, and query tuning.
  • Caching: Use @Cacheable with Redis or EhCache.
  • Thread Management: Configure thread pools for async tasks.
  • JVM Tuning: Adjust heap size and GC settings.
  • Lazy Initialization: Enable lazy loading to reduce startup time.
  • Reduce Logging Level: Avoid excessive logs in production.
Example: Enable Caching
@SpringBootApplication
@EnableCaching
public class AppConfig {
}
    
Key Points:
  • Use Actuator + Monitoring Tools for visibility.
  • Optimize DB, Cache, Threads, and JVM for performance.
  • Continuously track metrics and improve.
Q8: How are objects created in Spring Boot? Medium +
Object Creation in Spring Boot:
  • Objects (Beans) are created and managed by the Spring IoC Container.
  • Spring uses Dependency Injection (DI) to create and inject objects.
  • Developers don’t use new keyword directly for managed beans.
Ways to Create Objects (Beans): 1. Using @Component (Auto Detection)
@Component
public class UserService {
}
    
2. Using @Bean (Manual Configuration)
@Configuration
public class AppConfig {

    @Bean
    public UserService userService() {
        return new UserService();
    }
}
    
3. Using @Service, @Repository, @Controller
@Service
public class OrderService {
}
    
Dependency Injection Example:
@RestController
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }
}
    
Key Points:
  • Spring container controls object lifecycle.
  • Uses constructor injection (recommended).
  • Supports singleton (default) and prototype scopes.
Q9: What is default scope in Spring? Easy +
Default Scope:
  • The default scope in Spring is Singleton.
  • Only one instance of the bean is created per Spring container.
  • The same object is shared across the entire application.
Example:
@Component
public class UserService {
}
    
Key Points:
  • No need to explicitly define scope → Singleton is default.
  • Bean is created at application startup (eager initialization).
  • Best suited for stateless services.
Q10: What is the use of @Profile in Spring Boot? Medium +
@Profile:
  • Used to activate beans based on environment (dev, test, prod).
  • Allows loading different configurations for different environments.
  • Helps in environment-specific bean creation.
Example:
@Configuration
@Profile("dev")
public class DevConfig {

    @Bean
    public DataSource dataSource() {
        return new H2DataSource();
    }
}
    
Another Example:
@Service
@Profile("prod")
public class PaymentService {
}
    
How to Activate Profile:
spring.profiles.active=dev
    
Key Points:
  • Only beans with active profile are loaded.
  • Common profiles → dev, test, prod.
  • Improves configuration management and flexibility.
Q11: What is difference between PUT and POST? Easy +
POST:
  • Used to create a new resource.
  • Server generates the resource ID.
  • Not idempotent → multiple calls create multiple records.
Example:
@PostMapping("/users")
public User createUser(@RequestBody User user) {
    return userService.save(user);
}
    
PUT:
  • Used to update an existing resource (or create if not exists).
  • Client provides the resource ID.
  • Idempotent → multiple calls give same result.
Example:
@PutMapping("/users/{id}")
public User updateUser(@PathVariable int id, @RequestBody User user) {
    return userService.update(id, user);
}
    
Key Difference:
  • POST → Create new resource
  • PUT → Update existing resource
  • POST → Non-idempotent
  • PUT → Idempotent

🔥 Ready to Master Spring Boot?

Follow us for real-world Microservices projects and Spring Security deep-dives!

Finished studying this topic?

Return to Home Page

Comments

More Related

For Any Help Related to coding exams follow me on Instagram : codingsolution75

Popular Posts

EPAM Latest Coding Questions with Solutions 2026

Java Interview Questions

Fresco Play Hands-on Latest Solutions

Accenture Latest Coding Questions with Solutions

MindTree Latest Coding Questions with Solutions

Infosys | InfytTq | Infosys Certification Exam Latest Coding Questions with Solutions

LTI (Larsen & Toubro Infotech ) Coding Questions and Solutions 2022-23

Cognizant

TCS Digital Exam | DCA | Direct Capability Assessment

TypeScript Complete Course With Completed Hands-on