Consider this Spring Boot service class using constructor injection. What will be printed when greet() is called?
import org.springframework.stereotype.Service; @Service public class GreetingService { private final String message; public GreetingService() { this.message = "Hello, World!"; } public String greet() { return message; } }
Look at how the message field is set in the constructor.
The constructor sets the message field to "Hello, World!". So calling greet() returns that string.
Choose the correct constructor injection syntax for a Spring Boot service that depends on DataService.
Remember constructors have no return type and parameters are assigned to fields.
Option D correctly defines a constructor with a parameter and assigns it to the field. Option D uses manual instantiation, not injection. Option D has a void return type, so it's a method, not a constructor. Option D assigns the parameter to itself, not the field.
Examine this Spring Boot component. Why will the dependency injection fail?
import org.springframework.stereotype.Component; @Component public class UserComponent { private final UserService userService; public UserComponent() { this.userService = null; } public String getUserName() { return userService.getName(); } }
Think about how Spring injects dependencies via constructors.
Spring injects dependencies by calling constructors with parameters. Here, the constructor has no parameters, so Spring cannot inject UserService. The field is set to null manually, causing a NullPointerException later.
Given this Spring Boot component using constructor injection, what will be the value of configValue after creation?
import org.springframework.stereotype.Component; @Component public class ConfigComponent { private final String configValue; public ConfigComponent(String configValue) { this.configValue = configValue; } public String getConfigValue() { return configValue; } }
Think about how Spring injects simple types like String in constructors.
Spring cannot inject a String parameter without additional annotations like @Value or configuration. Without them, Spring cannot resolve the constructor parameter, so the component creation fails or the field remains null if forced.
Choose the best explanation why constructor injection is preferred in Spring Boot applications.
Think about immutability and testing benefits.
Constructor injection makes dependencies final and required, which helps avoid nulls and makes testing easier. It also clarifies what dependencies a class needs. Other options are incorrect or misleading.