Class A {
private B instanceB;
@Autowired
public setInstanceB(B instanceB) {
this.instanceB = instanceB;
}
}
Above one versus this one.
Class A {
@Autowired
private B instanceB;
public setInstanceB(B instanceB) {
this.instanceB = instanceB;
}
}
Will the behavior differ based on the access modifier ?
It is the default autowiring mode. It means no autowiring bydefault. The byName mode injects the object dependency according to name of the bean. In such case, property name and bean name must be same.
The XML-configuration-based autowiring functionality has five modes – no , byName , byType , constructor , and autodetect .
You can annotate fields and constructor using @Autowired to tell Spring framework to find dependencies for you. The @Inject annotation also serves the same purpose, but the main difference between them is that @Inject is a standard annotation for dependency injection and @Autowired is spring specific.
The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.
The difference is the setter will be called if that's where you put it, which is useful if it does other useful stuff, validation, etc. Usually you're comparing:
public class A {
private B instanceB;
@Autowired
public setInstanceB(B instanceB) {
this.instanceB = instanceB;
}
}
vs
public class A {
@Autowired
private B instanceB;
}
(ie there is no setter).
The first is preferable in this situation because lack of a setter makes mocking/unit testing more difficult. Even if you have a setter but autowire the data member you can create a problem if the setter does something different. This would invalidate your unit testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With