Autowired annotations used when doing DI in Spring are easy to use and convenient! However, there are multiple ways to use it, and I am at a loss as to which one to use. I often use it in constructors, but I would like to sort out how that happened.
Rough review. There are three ways to set Autowired.
This is a type of declaration method that is written directly in the field.
public class A {
@Autowired
private B b;
}
This is the type of declaration method to write in the constructor.
public class A {
private final B b;
@Autowired
public A(B b) {
this.b = b;
}
}
It is a type of declaration method to write in the setter.
public class A {
private B b;
@Autowired
public void setB(B b) {
this.b = b;
}
}
Final can be used for the field to ensure immutability. The reason for this is great. By doing this, it is safe because it will not be rewritten in the middle of processing. (Even people who don't understand in maintenance will get a compile error when rewriting final. Really) Also, it is great that you can make a new test. Personally, I'm happy to be able to choose between DI in the test or just new.
In the first place, it is deprecated by the official. (Sure) There would be no point in using it.
I don't trust the sample source to use field injection. I personally think it's no good. (It's really easy)
Let's use constructor injection without getting tired of any source.
Recommended Posts