2020년 5월 23일 토요일

[Spring] Auto-injection of dependency using @Autowired, @Resource, @Inject

Dependency automatic injection 

 Previously, posts set xml files to inject dependency and wrote Java code. However, the dependency can be injected automatically using @Resource, @Autowired, and @Inject. As shown in the example below, we will only register the classes as empty and try to inject them automatically using the annotation.
example
@Configuration
public class Config {
 
    @Bean 
    public A a1() {
     return new A();
    }
    
    @Bean
    public A a2() {
     return new A();
    }
    
    @Bean
    public B b() {
     return new B();
    }
}

@Resource 

 @Resource is Java-supported annotations that look at the name of the object and explore which classes to inject depending on.
example
public class Normal {
 
    @Resource
    private A a1;
    
    public String method() {
     String str = a1.method();
    }
}
 When you attach @Resource to the a1 field, the object is injected into the Normal class as it is associated with a method named a1 in the class where you registered the bin. Because of the dependent injection, a1 can be used if you are in a normal class.

@Resource
private A b; // 오류 발생
 However, if you do this above, @Resource will connect to the b method that creates the B object, and the current type is declared as Class A, so it will be an error because the type does not match.

@Resource(name="a1")
private A b;
 In this case, you can correct the error by specifying a specific method by using the name attribute in the Annotation.

@Autowired, @Inject

 These two annunciations look at the type of object and explore and use the class to be injected. The only difference is that @Autowired is supported by the spring and @Inject is supported by Java.
example
public class Normal {
 
    @Autowired
    @Qulified("a1")
    private A a;
    
    public String method() {
     String str = a.method();
    }
}
 Since the type of field a is Class A, it is associated with the method that generates the object A among the methods registered as bins. Since there are two methods to create the A object, you have associated it with a specific method through the @Quired Annotation.

@Autowired
private A a1; // 오류

@Autowired
private A a2; // 오류
 Because @Autowired looks for objects to be injected as type, injecting multiple objects of the same type results in an error because they cannot find the target. To avoid errors, you can connect to a specific method with @Qualified to resolve them.

댓글 없음:

댓글 쓰기