Search Tutorials


Spring Boot Quiz - MCQ - Multiple Choice Questions | JavaInUse

Spring Boot Quiz - MCQ - Multiple Choice Questions

Q. For the following spring boot code

@SpringBootApplication
public class MyApp {

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
  
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");
        dataSource.setUsername("root");
        dataSource.setPassword("password");
        return dataSource;
    }
  
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
  
    @Autowired
    private JdbcTemplate jdbcTemplate;
  
    // Rest of the application code...
}
A. The `dataSource` bean will be automatically picked up by Spring Boot and configured as the application's primary `DataSource`.
B. The `jdbcTemplate` bean will be automatically created by Spring Boot using the `dataSource` bean defined in the `dataSource()` method.
C. The `dataSource` bean will be created but won't be used by Spring Boot unless explicitly injected into a component.
D. The application will fail to start because there is no `@RestController` or `@Controller` class defined in the code snippet.

Q. What is Spring Initializer primarily used for?

A. Generating boilerplate code for Spring Boot applications.
B. Running Spring Boot applications.
C. Debugging Spring Boot applications.
D. Deploying Spring Boot applications.

Q. Which of the following is true about Spring Security?

A. Spring Security provides authentication and authorization support for Spring-based applications.
B. Spring Security is only applicable to web applications.
C. Spring Security cannot be integrated with other Spring modules.
D. Spring Security has no out-of-the-box support for implementing multi-factor authentication.

Q. Which of the following statements is true about Spring AOP (Aspect-Oriented Programming)?

A. Spring AOP is only used for exception handling in Spring applications.
B. Spring AOP can only be used with Spring MVC applications.
C. Spring AOP is primarily used for database access and transaction management.
D. Spring AOP allows cross-cutting concerns to be separated from the business logic.

Q. Which of the following statements is true about Spring Database integration?

A. Spring provides a built-in relational database management system.
B. Spring only supports SQL Server and Oracle integration.
C. Spring supports database access through JDBC and ORM frameworks.
D. Spring database integration is limited to NoSQL stores.

Q. Which of the following is true about Spring Boot?

A. Spring Boot is a completely separate framework, unrelated to Spring.
B. Spring Boot requires manual configuration for everything.
C. Spring Boot speeds development with opinionated defaults and auto-configuration.
D. Spring Boot only fits very small applications.

Q. Which Spring Boot annotation marks the main application class?

A. @Component
B. @Service
C. @RestController
D. @SpringBootApplication

Q. Which statement about the @Autowired annotation in Spring Boot is true?

A. @Autowired injects Spring-managed dependencies into application components.
B. @Autowired only works for String dependencies.
C. @Autowired is optional and never needed for dependency injection.
D. @Autowired is mandatory and limited to service classes.

Q. Which code snippet shows the correct Spring Boot REST Controller configuration?

A. Uses `@RestController` with `@GetMapping` to expose `/hello`.
@RestController
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}
                

B. Uses `@Controller` with `@RequestMapping` at the class level only.
@Controller
@RequestMapping("/api")
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}
                

C. Combines `@RestController` and `@RequestMapping`, but not HTTP method-specific mappings.
@RestController
@RequestMapping("/api")
public class MyController {
    @RequestMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}
                

D. Uses `@Controller` plus `@ResponseBody` at the method level.
@Controller
public class MyController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    @ResponseBody
    public String hello() {
        return "Hello, World!";
    }
}
                





Q. Which code snippet correctly defines a Spring Boot service class?

A. Annotates the class with `@Service` and uses constructor injection.
@Service
public class MyService {
    private final MyRepository myRepository;

    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

    // Service methods here
}
                

B. Uses `@Component` plus constructor injection.
@Component
public class MyService {
    private final MyRepository myRepository;

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

    // Service methods here
}
                

C. Uses `@Controller` for a service class.
@Controller
public class MyService {
    private final MyRepository myRepository;

    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

    // Service methods here
}
                

D. Adds `@RequestMapping` to a service class.
@Service
@RequestMapping("/service")
public class MyService {
    private final MyRepository myRepository;

    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

    // Service methods here
}
                

Q. Which snippet correctly configures a Spring Boot application class?

A. Uses `@Configuration` only.
@Configuration
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}
                

B. Uses `@SpringBootApplication`.
@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}
                

C. Annotates the main class with `@RestController`.
@RestController
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}
                

D. Uses `@Component` for the application entry point.
@Component
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}
                

Q. Which snippet secures a Spring Boot REST API correctly?

A. Restricts `/api/**` to admins only and disables CSRF.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/api/**").hasRole("ADMIN")
                .anyRequest().permitAll()
                .and()
            .httpBasic();
    }
}
                

B. Makes `/api/**` authenticated but never disables CSRF.
@SpringBootApplication
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/api/**").authenticated()
                .anyRequest().permitAll()
                .and()
            .httpBasic();
    }
}
                

C. Secures `/api/**`, leaves other endpoints public, uses HTTP Basic, and disables CSRF for stateless REST APIs.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/api/**").authenticated()
                .anyRequest().permitAll()
                .and()
            .httpBasic()
                .and()
            .csrf().disable();
    }
}
                

D. Leaves `/api/**` public and requires auth elsewhere.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/api/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .httpBasic();
    }
}
                

Q. Which snippet correctly configures Spring Boot AOP for logging method execution?

A. Uses `@Around` advice on a component aspect.
@Component
@Aspect
public class LoggingAspect {
    
    @Pointcut("execution(* com.example.*.*(..))")
    public void myPointcut() {}
    
    @Around("myPointcut()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Before method execution");
        Object result = joinPoint.proceed();
        System.out.println("After method execution");
        return result;
    }
}
                

B. Uses `@After` advice only.
@Configuration
@Aspect
public class LoggingAspect {
    
    @Pointcut("execution(* com.example.*.*(..))")
    public void myPointcut() {}
    
    @After("myPointcut()")
    public void afterAdvice() {
        System.out.println("After method execution");
    }
}
                

C. Uses `@AfterReturning` advice in a service bean.
@Service
@Aspect
public class LoggingAspect {
    
    @Pointcut("execution(* com.example.*.*(..))")
    public void myPointcut() {}
    
    @AfterReturning("myPointcut()")
    public void afterReturningAdvice() {
        System.out.println("After method execution");
    }
}
                

D. Uses `@Before` advice with `@Aspect` and `@Configuration`.
@Aspect
@Configuration
public class LoggingAspect {
    
    @Pointcut("execution(* com.example.*.*(..))")
    public void myPointcut() {}
    
    @Before("myPointcut()")
    public void beforeAdvice() {
        System.out.println("Before method execution");
    }
}
                

Q. Which snippet correctly configures Spring Boot to connect to PostgreSQL?

A. Relies on `@SpringBootApplication` only.
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
                

B. Defines a manual `DataSource` bean.
@Configuration
public class DatabaseConfig {

    @Value("")
    private String url;

    @Value("")
    private String username;

    @Value("")
    private String password;

    @Bean
    public DataSource dataSource() {
        return DataSourceBuilder
                .create()
                .url(url)
                .username(username)
                .password(password)
                .build();
    }
}
                

C. Uses `@SpringBootApplication` plus `@EnableAutoConfiguration` to let Boot configure the datasource from properties.
@SpringBootApplication
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
                

D. Enables JPA repositories only.
@Configuration
@EnableJpaRepositories(basePackages = "com.example.repositories")
public class DatabaseConfig {

    // Other configuration properties and beans here
}
                

Q. Which snippet properly configures Spring Boot for a batch processing job?

A. Defines only the main application entry point.
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
                

B. Enables batch processing but defines no infrastructure beans.
@Configuration
@EnableBatchProcessing
public class BatchConfig {

    // Batch job and step configurations here
}
                

C. Uses a REST controller for batch configuration.
@RestController
public class MyController {

    // Batch job and step configurations here
}
                

D. Enables batch processing and injects the required builder factories.
@Configuration
@EnableBatchProcessing
public class BatchConfig {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    // Batch job and step configurations here
}
                

Q. Which file is most commonly used to externalize Spring Boot configuration?

A. bootstrap.yml
B. application.properties
C. config.ini
D. settings.json

Q. How do you enable a Spring profile at runtime?

A. Add `spring.profiles.active=prod` to application.properties
B. Start with `--spring.profiles.active=prod`
C. Set `SPRING_PROFILES_ACTIVE=prod` environment variable
D. Any of the above options

Q. What does the Spring Boot Actuator dependency provide?

A. Only database migrations
B. Production-ready endpoints for health, metrics, and info
C. Only logging configuration
D. A web server replacement

Q. Which annotation binds external properties to a POJO?

A. @Value
B. @ConfigurationProperties
C. @Bean
D. @ComponentScan

Q. Which starter adds both Spring MVC and an embedded Tomcat server?

A. spring-boot-starter-jdbc
B. spring-boot-starter-web
C. spring-boot-starter-aop
D. spring-boot-starter-test

Q. How do you expose Actuator endpoints over HTTP in Spring Boot 3 by default?

A. They are all exposed automatically
B. Set `management.endpoints.web.exposure.include=*`
C. Add `@EnableActuatorWeb` on a config class
D. Enable `spring.main.web-application-type=none`

Q. What does `spring-boot-starter-data-jpa` implicitly include?

A. Hibernate and Spring Data JPA
B. Only JDBC drivers
C. Embedded MongoDB
D. Kafka Streams support

Q. How do you disable the whitelabel error page in Spring Boot?

A. Remove Spring Boot from the classpath
B. Set `server.error.whitelabel.enabled=false`
C. Enable `spring.main.web-application-type=reactive`
D. Use `@RestController` on the main class

Q. Which annotation enables method-level validation on a Spring MVC controller?

A. @EnableValidation
B. @Validated
C. @AssertTrue
D. @ResponseStatus

Q. What is the default embedded server for Spring Boot Web?

A. Tomcat
B. Jetty
C. Undertow
D. Netty

Q. What happens when you annotate a class with `@RestController`?

A. It registers only WebSocket endpoints
B. It combines `@Controller` and `@ResponseBody` semantics
C. It disables view resolution completely
D. It enables CORS automatically for all origins

Q. How do you customize the application banner on startup?

A. Place banner.txt on the classpath
B. Override `SpringApplication.run()`
C. Rename application.properties to banner.properties
D. Add `@EnableBanner` to the main class

Q. Which actuator endpoint shows application health?

A. /actuator/env
B. /actuator/health
C. /actuator/mappings
D. /actuator/startup

Q. Which dependency adds reactive web support in Spring Boot?

A. spring-boot-starter-web
B. spring-boot-starter-webflux
C. spring-boot-starter-rsocket
D. spring-boot-starter-aop

Q. What does `@SpringBootTest` do in tests?

A. Starts no context; it is a marker only
B. Bootstraps the full Spring context for integration testing
C. Only mocks controllers
D. Disables auto-configuration

Q. Which property sets the HTTP port for an embedded server?

A. server.port
B. spring.web.port
C. spring.server.http
D. port.server

Q. How do you exclude a specific auto-configuration class?

A. Remove the dependency from pom.xml only
B. Use `@SpringBootApplication(exclude = ...)`
C. Annotate the class with `@DisableAutoConfig`
D. Set `spring.main.skip=true`

Q. Which dependency is best for testing JPA repositories?

A. spring-boot-starter-test only
B. spring-boot-starter-jdbc
C. spring-boot-starter-data-jpa
D. spring-boot-starter-actuator

Q. Which annotation do you use to schedule tasks in Spring Boot?

A. @Async
B. @Scheduled
C. @EnableAsync
D. @PostConstruct

Q. Which logback file does Spring Boot auto-detect by default?

A. logback.xml
B. logback-spring.xml
C. logging.properties
D. logger.xml

Popular Posts