Consider a Spring Boot application where a class is annotated with @Service. What is the main purpose of this annotation?
Think about where business rules and logic usually reside in a Spring Boot app.
The @Service annotation tells Spring that this class holds business logic and should be managed as a Spring bean, allowing it to be injected where needed.
Given a Spring Boot app where a class contains business logic but is not annotated with @Service or any stereotype, what will happen when another component tries to inject it?
Think about how Spring knows which classes to manage as beans.
Without @Service or another stereotype annotation, Spring does not register the class as a bean, so injection fails with NoSuchBeanDefinitionException.
Choose the correct way to define a Spring Boot service class using @Service and constructor-based dependency injection for a repository.
public interface UserRepository { /* methods */ }
// Choose the correct service class below:Constructor injection requires a constructor with parameters and final fields for immutability.
Option B correctly uses constructor injection with a final field and a constructor. Option B uses field injection which is discouraged. Option B has a method named like a constructor but with void return type, so it's not a constructor. Option B has no injection at all.
Given two service classes annotated with @Service that inject each other via constructor injection, what is the cause of the circular dependency error?
import org.springframework.stereotype.Service; @Service public class ServiceA { private final ServiceB serviceB; public ServiceA(ServiceB serviceB) { this.serviceB = serviceB; } } @Service public class ServiceB { private final ServiceA serviceA; public ServiceB(ServiceA serviceA) { this.serviceA = serviceA; } }
Think about how Spring creates beans and resolves dependencies.
Constructor injection requires all dependencies to be created first. When two services depend on each other via constructors, Spring cannot create either bean, causing a circular dependency error.
Both @Service and @Component annotations register a class as a Spring bean. What is the key conceptual difference between them?
Think about the purpose of stereotype annotations in Spring.
@Service is a specialized form of @Component that semantically indicates the class contains business logic. It helps readability and can be used by tools for specific processing. @Component is a generic annotation for any Spring-managed bean.