Spring @Autowired fields - which access modifier, private or package-private?

vikingsteve picture vikingsteve · Oct 30, 2013 · Viewed 20.6k times · Source

Let's say that we use the @Autowired annotation over various fields in a class, and that we didn't write setters or constructors that can also set the fields.

Question - what should the access modifier be, private or package-private (i.e. none) ?

For example:

public class MyClass {
    @Autowired
    private MyService myService;
}

vs

public class MyClass {
    @Autowired
    MyService myService;
}

In the first case (private fields) Spring uses reflection to wire up the field, even if it doesn't have a setter.

The second case (package-private fields) allows us to be able to access those fields (for example, to set up mocks) if we need to extend the class for testing purposes.

So both cases work fine, but which is more recommended, particularly with regards to testing?

Answer

Debojit Saikia picture Debojit Saikia · Oct 30, 2013

So both cases work fine, but which is more recommended, particularly with regards to testing?

I think the properties should be private:

@Autowired
private MyService myService;

As it is always good to have getter methods to provide access to the properties instead of allowing other classes to have direct access to them.

And for testing purposes, injection of mocks of private properties will work the same way as that of package-private properties.

For example, with Mockito, you can inject a mock of private MyService into MyClass as this:

public class MyClassTest {

    @Mock
    MyService service;

    @InjectMocks
    MyClass serv = new MyClass();

    @Before
    public void init() {
    MockitoAnnotations.initMocks(this);
    }
}