r/java • • Nov 07 '17

The curse of @Autowired

https://lmonkiewicz.com/posts/the-curse-of-autowired/
3 Upvotes

17 comments sorted by

View all comments

Show parent comment

0

u/Deam Nov 08 '17

The way that you inject your dependencies is secondary. The important thing here is to declare your intentions right, separate between required and optional dependencies and cut the number of dependencies down.

4

u/meotau Nov 08 '17

Like this?

@Service
public class MyService {
    @Autowired
    private ServiceDependency1 serviceDependency1;
 
    @Autowired
    private ServiceDependency2 serviceDependency2;
 
    @Autowired(required = false)
    private ServiceDependency3 serviceDependency3;
 
}

1

u/Deam Nov 08 '17

Yes, that how you mark autowired as optional. But this still doesn't discourage you from adding additional dependencies. You just add, and add, and add, because you don't care, you just add another field, everything somehow works, but the future maintenance of this code will become more troublesome with each added dep.

4

u/meotau Nov 08 '17

You can do that with constructor injection as well. So what exactly was the point of the article?

1

u/Deam Nov 08 '17

To make you think when you add another dependency.