Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't Spring's dependency injection break information hiding?

Coming from a C++ background I have to master the complexity of the Java world and its frameworks. Looking at the spring framework for DI I am finding it difficult to believe that I have to make each setter function which will be subject for DI public. Doesn't that requirement break the principle of information hiding?

Of course I want spring to be able to set some private parts of my classes, but I certainly do NOT want every client class to be able to do the same.

What am I missing here?

like image 472
struppi Avatar asked Mar 09 '09 20:03

struppi


People also ask

Why Autowired field injection is not recommended?

The reasons why field injection is frowned upon are as follows: You cannot create immutable objects, as you can with constructor injection. Your classes have tight coupling with your DI container and cannot be used outside of it. Your classes cannot be instantiated (for example in unit tests) without reflection.

Does dependency injection break encapsulation?

However, using any of the common IoC containers to service your Dependency Injection needs typically breaks Assembly Encapsulation by making everything public to work.

What problems does dependency injection solve?

The goal of the dependency injection technique is to remove this dependency by separating the usage from the creation of the object. This reduces the amount of required boilerplate code and improves flexibility.

What is the main purpose of using dependency injection?

Dependency injection helps to develop testable code, allowing developers to write unit tests easily. You can use mock databases with dependency injection, and test your application without affecting the actual database. Here's an example.


2 Answers

I agree with your point - that's why I prefer constructor injection.

like image 60
duffymo Avatar answered Oct 14 '22 00:10

duffymo


If you code to interfaces, you only need to expose setters on the implementations. As you inject the interfaces into other parts of the system, they cannot access the implementation details or state of the objects.

like image 30
oxbow_lakes Avatar answered Oct 13 '22 23:10

oxbow_lakes