Java – spring @ Autowired field – which access modifier, private or package private?

Suppose we use @ Autowired annotation on each field in the class, and we can set the setter or constructor of the field without writing

Question – should the access modifier be private or 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 connect fields, even if it doesn't have a setter

The second case (package private fields) allows us to access these fields (for example, set ridicule) if we need to extend the class for testing

So both of these situations work normally, but what is more recommended, especially in testing?

Solution

The first case also allows you to inject simulations based on the framework For example, use the @ injectmocks annotation of mockito There is also reflectiontestutils in spring test setField,…

Personally, I don't like to modify the course too much for testing purposes, so I will go to the first case But at the end of the day, it depends on your preferred testing framework

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>