Prompt
When working with Spring annotations, follow these guidelines to avoid common issues:
- Use interface types for dependency injection: When autowiring dependencies, declare fields using the interface type rather than the implementation class. This ensures proper behavior with proxies and AOP.
// RECOMMENDED
@Autowired
private Pojo self; // Interface type
// AVOID (unless you're certain CGLIB proxies are being used)
@Autowired
private SimplePojo self; // Implementation type
-
Remember @Bean flexibility: Methods annotated with
@Beancan be defined in any@Component-annotated class, not just in@Configurationclasses. -
Avoid annotation-based injection in infrastructure classes: Do not use
@Autowired,@Inject, or@Resourceannotations within BeanFactory implementations or their dependencies. This can causeBeanCurrentlyInCreationExceptiondue to initialization timing issues. Use programmatic lookups instead for these infrastructure components.
Following these practices will help prevent subtle runtime errors and improve the maintainability of your Spring applications.