Performance: @Autowired for dependency injection
@Autowired affects application startup time and memory usage by managing object creation and wiring dependencies automatically.
public class Service {
@Autowired
private Repository repo;
}public class Service {
private Repository repo = new Repository();
}| Pattern | Bean Creation | Dependency Resolution | Memory Usage | Verdict |
|---|---|---|---|---|
| Manual new operator | Multiple independent instances | No automatic resolution | Higher due to duplicates | [X] Bad |
| @Autowired field injection | Singleton beans reused | Automatic resolution at startup | Optimized by Spring container | [OK] Good |
@Autowired annotation in Spring Boot?@Autowired for field injection in a Spring Boot class?myController.printServiceName() is called?
@Service
public class MyService {
public String getName() { return "ServiceA"; }
}
@RestController
public class MyController {
@Autowired
private MyService myService;
public void printServiceName() {
System.out.println(myService.getName());
}
}
@Service
public class UserService {
private Repository repo;
@Autowired
public void setRepo(Repository repo) {
this.repo = repo;
}
}
@RestController
public class UserController {
@Autowired
private UserService userService;
public void doSomething() {
userService.repo.save();
}
}
PaymentService into a controller using @Autowired. How can you specify which implementation to inject?Pass the test and this pattern moves unknown