Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject into private, package or public field or provide a setter?

I see many Java examples using dependency injection with private fields without a public setter like this:

public SomeClass {
  @Inject
  private SomeResource resource;
}

But that is a bad idea when the injection should be performed manually for example in unit tests.

There are several possibilities to solve this:

  • add a public setter: setSomeResource(SomeResource r)
  • make the field public
  • make the field package protected

I'd like to avoid the setter, since nothing really happens in it. So I'd prefer public or package protected. What do you recommend?

like image 270
deamon Avatar asked Jan 07 '10 16:01

deamon


People also ask

Is field injection same as setter injection?

Field Injection uses reflection to set the values of private variables. Constructor Injection happens at the time of creating the object itself. Setter Injection uses setters to set the value.

When should setter injection be used?

Use Setter injection when a number of dependencies are more or you need readability. Use Constructor Injection when Object must be created with all of its dependency.

Which is better setter or constructor injection in Spring?

Constructor-based DI fixes the order in which the dependencies need to be injected. Setter-based DI helps us to inject the dependency only when it is required, as opposed to requiring it at construction time. Spring code generation library doesn't support constructor injection so it will not be able to create proxy.


1 Answers

One way to avoid creating a setter for the field is using constructor injection. This even allows you to declare the field as final.

It goes like this:

public class SomeClass {
    private final SomeResource resource;

    @Inject
    public SomeClass(SomeResource resource) {
        this.resource = resource;
    }
}
like image 153
Andre Rodrigues Avatar answered Sep 20 '22 14:09

Andre Rodrigues