Performance: @Service annotation
This affects application startup time and memory usage by managing service bean creation and lifecycle.
Jump into concepts and practice - no test required
@Service public class UserService { public void process() { /* logic */ } } // Injected by Spring where needed
public class UserService { public void process() { /* logic */ } } // Instantiated manually in controllers or other classes
| Pattern | Bean Management | Startup Impact | Memory Usage | Verdict |
|---|---|---|---|---|
| Manual Instantiation | No container management | Slower due to repeated creation | Higher due to multiple instances | [X] Bad |
| @Service Annotation | Singleton managed by Spring | Faster startup with reuse | Lower due to single instance | [OK] Good |
@Service annotation in Spring Boot?@Service@Service annotation is used to mark classes that hold business logic in the service layer.@Entity), REST controllers (@RestController), or configuration (@Configuration).@Service in Spring Boot?@Service before the class declaration. Options B, C, and D have incorrect placement or syntax.myService.greet() is called?@Service
public class MyService {
public String greet() {
return "Hello from Service!";
}
}greet() method returns the string "Hello from Service!" when called.public class UserService {
@Service
public void saveUser() {
// save logic
}
}@Service annotation is meant for classes, not methods.@Autowired. The class does not need to extend any base class.@Service and @Autowired together to follow Spring Boot best practices?@Service
public class OrderService {
private final OrderRepository orderRepository;
// Constructor here
}@Autowired is preferred for mandatory dependencies.@Service and constructor injection@Service and create a constructor with @Autowired to inject OrderRepository.