Question

When should I autowire a resource rather than pass it by value into the constructor and set it to be private.

For example,

@Autowired
private SystemLogger systemLogger

vs

public class derp {
 private SystemLogger systemLogger;   
 public derp(SystemLogger systemLogger){
        this.systemLogger = systemLogger;
    }
}
Was it helpful?

Solution

Since the SystemLogger would seem to be an integral part of your class, I would pass it as a constructor argument. Personally, I think it makes it more obvious which collaborators your class needs to be properly initialised. It should also be final.

This also has the benefit of making your class easier to test using mocks. You could use mocks using Autowired on an attibute, but it would involve more effort (e.g. exposing a setter - which would be bad, or shoe-horning a mock into the ApplicationContext).

This may just come down to personal preference, but for what it's worth, the Spring Consultant that led the Core Spring Training I attended recommended not using Autowired on class members.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top