Anti-Patterns that You should avoid in Spring

Bad Practices in Spring

Ali Zeynalli
3 min readAug 28, 2021
Photo by Alin Andersen on Unsplash

Spring Framework with its on-top implementations of Spring Boot and Spring MVC are the most common frameworks that are used in Java world. The more it is used, the more bad and good practices emerge over time. On the other hand, being opinionated makes Spring Boot more strict with guidelines. Without much talk, I will try to point out some anti-patterns in this article that should be avoided from Spring Developers.

Spring DI: Favour Construction Injection over Field and Setter Injection

Field injected beans are hard to test, prone to circular dependencies and are extremely open mutability. In order to make dependency final @Autowired variable needs extra annotations (@Autowired(required = false) or @Lazy). The same drawbacks are seen at Setter Injection. Additionally, Setter Injection causes boilerplate code. The best solution here is to use constructor injection which is also officially recommended by Spring. With this method variables can be made easily immutable. Dependency growth is detected easily since constructor grows.

--

--

Ali Zeynalli

IT-Architect | BMW Group | M.Sc. Technical University of Berlin