🌱 Spring Boot MCQ Questions – Page 37

Questions 721–740 of 971 total — Spring Boot interview practice

▶ Practice All Spring Boot Questions
Q721 medium code error
A `CustomerService` class has an `@Autowired` `CustomerRepository` (which is a `@Repository` bean). If `CustomerService` is instantiated directly using `new CustomerService()` in a `main` method or a JUnit test without loading a Spring application context, what will happen when `getCustomerInfo()` is called?
java
package com.example.repository;
import org.springframework.stereotype.Repository;

@Repository
public class CustomerRepository {
    public String findCustomerName(Long id) { return "Customer_" + id; }
}

package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.repository.CustomerRepository;

@Service
public class CustomerService {
    @Autowired
    private CustomerRepository customerRepository;

    public String getCustomerInfo(Long id) {
        return customerRepository.findCustomerName(id); // This line will fail
    }
}

package com.example.test;
public class CustomerServiceTest {
    public static void main(String[] args) {
        CustomerService service = new CustomerService(); // NOT a Spring-managed bean
        String info = service.getCustomerInfo(1L);
        System.out.println(info);
    }
}
Q722 medium code output
What is the output when attempting to parse a malformed JWT string using JJWT?
java
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import java.security.Key;

public class MalformedJwtHandler {
    public static void main(String[] args) {
        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String malformedJwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ.invalid_payload.invalid_signature"; // Missing dot after header
        try {
            Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(malformedJwt);
            System.out.println("Parsed successfully");
        } catch (MalformedJwtException e) {
            System.out.println("MalformedJwtException caught");
        } catch (Exception e) {
            System.out.println("Other exception: " + e.getClass().getSimpleName());
        }
    }
}
Q723 medium code error
What is the expected error when a client sends a GET request to /items?
java
import org.springframework.web.bind.annotation.*;

@RestController
public class ItemController {

    @PostMapping("/items")
    public String createItem(@RequestBody String itemDetails) {
        return "Item created: " + itemDetails;
    }
}
Q724 medium code output
What value will the 'user' attribute in the Model hold after the `saveUser` method is invoked with a form submission 'username=Diana'?
java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

// Assume User class exists with String username and its getters/setters
// public class User { private String username; /*getters/setters*/ }

@Controller
public class UserFormController {
    @PostMapping("/user/save")
    public String saveUser(@ModelAttribute("myUser") User user, Model model) {
        model.addAttribute("user", user);
        return "user_profile";
    }
}
Q725 medium code output
What is the effective command that the Docker container will execute given this Dockerfile?
dockerfile
FROM openjdk:17-jre-slim
WORKDIR /app
COPY target/my-app.jar app.jar
ENTRYPOINT ["java", "-jar"]
CMD ["app.jar", "--server.port=9090"]
Q726 medium
How can you disable specific auto-configurations provided by `@EnableAutoConfiguration` within `@SpringBootApplication`?
Q727 medium
On which of the following elements can the `@Qualifier` annotation be applied in Spring for autowiring purposes?
Q728 medium code error
What error will occur during Spring Boot application startup with the following component and configuration?
java
java
@Component
public class AppSettings {
    @Value("${app.max-attempts}")
    private int maxAttempts;

    public int getMaxAttempts() {
        return maxAttempts;
    }
}


properties
# application.properties
app.max-attempts=ten
Q729 medium code error
What is the most likely error if the `getUserData` method in `UserService` is invoked after application startup?
java
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Repository;

@Repository
class UserRepository {
    public String findById(Long id) { return "User " + id; }
}

@Service
public class UserService {
    private UserRepository userRepository; // Missing @Autowired

    public String getUserData(Long id) {
        return userRepository.findById(id);
    }
}
Q730 medium code output
What is the output of this code snippet, which generates a token with an 'audience' claim and then attempts to retrieve it?
java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;

public class AudienceClaimTest {
    public static void main(String[] args) {
        Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String audience = "web_app";
        String jwt = Jwts.builder()
                .setSubject("client1")
                .setAudience(audience)
                .signWith(key)
                .compact();
        
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(jwt)
                .getBody();
        System.out.println(claims.getAudience());
    }
}
Q731 medium code output
What is the output of this code when `App` is executed?
java
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.annotation.*;

class MyDestroyBean implements DisposableBean {
    public MyDestroyBean() { System.out.println("1. Ctor"); }
    @PreDestroy public void preDestroy() { System.out.println("2. @PreDestroy"); }
    @Override
    public void destroy() { System.out.println("3. DisposableBean.destroy"); }
    public void customDestroy() { System.out.println("4. customDestroyMethod"); }
}
@Configuration
public class App {
    @Bean(destroyMethod = "customDestroy") public MyDestroyBean myDestroyBean() { return new MyDestroyBean(); }
    public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class); System.out.println("5. Closing context..."); context.close(); System.out.println("6. Context closed."); }
}
Q732 medium code error
What error will occur when this Spring Boot application attempts to start if it tries to use JPA repositories?
java
package com.example.app;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.data.jpa.repository.JpaRepository;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DataApp {
    public static void main(String[] args) {
        SpringApplication.run(DataApp.class, args);
    }
}

interface MyRepository extends JpaRepository<Object, Long> {}
Q733 medium code error
What runtime error will occur if a GET request like `/api/products/abc` is made to the following controller?
java
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    @GetMapping("/{id}")
    public String getProductById(@PathVariable Integer id) {
        return "Product ID: " + id;
    }
}
Q734 medium code output
What is the HTTP status and body returned by the `registerUser` method when a POST request is made to `/users` with the JSON body `{"username": "john_doe"}` (Content-Type: application/json)?
java
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

class User {
    private String username;
    private String email;
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

@RestController
@RequestMapping("/users")
class UserController {
    @PostMapping
    public ResponseEntity<String> registerUser(@RequestBody User user) {
        return new ResponseEntity<>("User registered: " + user.getUsername() + ", " + user.getEmail(), HttpStatus.CREATED);
    }
}
Q735 medium code output
Given the following Spring Boot controller, what will be the value of the 'userName' variable within the 'processForm' method if a form is submitted with data 'firstName=Bob&age=25'?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class FormController {
    @PostMapping("/submit")
    public String processForm(
        @RequestParam(name = "firstName", required = false, defaultValue = "Guest") String userName,
        @RequestParam(name = "age") int userAge
    ) {
        // userName and userAge are used here
        return "result";
    }
}
Q736 medium code error
What error will occur when Spring attempts to instantiate `InnerComponent`?
java
import org.springframework.stereotype.Component;

public class OuterClass {
    @Component
    private static class InnerComponent {
        public String getName() { return "Inner"; }
    }
}
Q737 medium code output
Given `application.properties` contains `data.items=apple,banana,cherry` and the following Java code, what does it print?
java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class ItemService {
    @Value("${data.items}")
    private List<String> items;

    public int getItemCount() {
        return items.size();
    }
}
// In a Spring Boot application, if this component is scanned:
// ItemService service = applicationContext.getBean(ItemService.class);
// System.out.println(service.getItemCount());
Q738 medium code error
What is the result if the following Spring Boot controller method is executed, and a request is made to `/forwardedPage`?
java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;

@Controller
public class ForwardController {

    @GetMapping("/initialPage")
    public String initialPage(Model model) {
        model.addAttribute("data", "Forwarded Data");
        return "forward:/forwardedPage";
    }

    @GetMapping("/forwardedPage")
    public String forwardedPage(Model model) {
        // Assume forwardedPage.html tries to access ${data}
        return "forwardedPage"; 
    }
}
Q739 medium
What is the typical outcome in a Spring Boot application if a required dependency for an autowired field or constructor argument cannot be found in the `ApplicationContext` during application startup?
Q740 medium code output
What is the output of this code when `App` is executed?
java
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;

@Component
class MyBean implements InitializingBean {
    public MyBean() { System.out.println("1. Ctor"); }
    @PostConstruct public void postConstruct() { System.out.println("2. @PostConstruct"); }
    @Override
    public void afterPropertiesSet() { System.out.println("3. afterPropertiesSet"); }
}
@ComponentScan
public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(App.class);
        context.close();
    }
}
← Prev 3536373839 Next → Page 37 of 49 · 971 questions