반응형

Spring @Autowired Annotation


(원문 위치 : http://www.tutorialspoint.com/spring/spring_autowired_annotation.htm )

@Autowired annotation은 어디서 어떻게 autowiring이 만들어지는지에 대해 더 세밀한 제어를 제공한다. @Autowired annotation은 @Required annotation처럼 setter 함수, 생성자, 임의의 이름 그리고/또는 다수의 인자를 가진 속성(property) 또는 함수(method)에 autowire하기 위해 사용될 수 있다.

@Autowired on Setter Methods:

XML 설정파일에서 <property> 요소를 제거하기 위해 setter함수에서 @Autowired annotation을 사용할 수 있다. Spring이 setter함수에 @Autowired annotation을 발견하면, Spring은 함수에 'byType' autowiring을 수행하려고 시도한다.

Example


[003] HelloWorld Example 강좌를 참조하여 프로젝트를 생성한다.

TextEditor.javasetSpellChecker()에 @Autowired annotation이 사용되었다.

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
   private SpellChecker spellChecker;

   @Autowired
   public void setSpellChecker( SpellChecker spellChecker ){
      this.spellChecker = spellChecker;
   }
   public SpellChecker getSpellChecker( ) {
      return spellChecker;
   }
   public void spellCheck() {
      spellChecker.checkSpelling();
   }
}

SpellChecker.java:

package com.tutorialspoint;

public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }

   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
   
}

MainApp.java:

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      TextEditor te = (TextEditor) context.getBean("textEditor");

      te.spellCheck();
   }
}

Beans.xmltextEdiotr bean 정의부분에서 spellChecker를 인자로 넘기기 위한 <property>가 제거되었다.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>

   <!-- Definition for textEditor bean without constructor-arg  -->
   <bean id="textEditor" class="com.tutorialspoint.TextEditor">
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
   </bean>

</beans>

실행 결과는 아래와 같다.

Inside SpellChecker constructor.
Inside checkSpelling.


@Autowired on Properties:

setter함수를 제거하기 위해 속성(property>에 @Autowired annotation을 사용할 수 있다. <property>를 사용하여 auto wired 된 속성의 값을 전달할 때, Spring은 자동적으로 전달된 값(value) 또는 참조(reference)를 속성(property)에 할당한다.(assign) 


[003] HelloWorld Example 강좌를 참조하여 프로젝트를 생성한다.


TextEditor.java: spellChecer 속성(property)에 @Autowired가 선언되었고, setSpellChecker()함수가 없음을 알 수 있다.

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
   @Autowired
   private SpellChecker spellChecker;

   public TextEditor() {
      System.out.println("Inside TextEditor constructor." );
   }
   
   public SpellChecker getSpellChecker( ){
      return spellChecker;
   }
   
   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}

SpellChecker.java:

package com.tutorialspoint;

public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }

   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
   
}

Beans.xml: 여기서도 또한 textEditor bean정의에서 spellChecker를 전달하기 위한 <property>가 없다.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>

   <!-- Definition for textEditor bean -->
   <bean id="textEditor" class="com.tutorialspoint.TextEditor">
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
   </bean>

</beans>

실행 결과는 아래와 같다.

Inside TextEditor constructor.
Inside SpellChecker constructor.
Inside checkSpelling.


@Autowired on Constructors:

@Autowired는 생성자에도 적용할 수 있다. 생성자 @Autowired annotation은 생성자가 비록 <constructor-arg> 요소가 XML파일에서 bean을 설정하는 동안 사용되지 않았을지라도 bean을 생성할 때 autowired 되어질 수 있음을 나타낸다.


TextEditor.java생성자(TextEditor)에 @Autowired annotation이 사용되었다.

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
   private SpellChecker spellChecker;

   @Autowired
   public TextEditor(SpellChecker spellChecker){
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }

   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}

Beans.xml이전 예제와는 다르게 이 예제의 경우 생성자를 이용한 DI의 구현이므로 일반적인 Beans.xml인 경우, textEditor bean의 정의에서 <constructor-arg>를 이용하여 spellChecker를 생성자의 인자로 전달하여야 하지만, textEditor의 생성자에 @Autowired를 사용함으로서 제거되었다.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>

   <!-- Definition for textEditor bean without constructor-arg  -->
   <bean id="textEditor" class="com.tutorialspoint.TextEditor">
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
   </bean>

</beans>

실행 결과는 아래와 같다.

Inside TextEditor constructor.
Inside SpellChecker constructor.
Inside checkSpelling.

@Autowired with (required=false) option

기본적으로 @Autowired annotation은 의존관계가 @Required annotation과 유사하게 필수값임을 나타낸다. 하지만, @Autowired와 (required=false) 옵션을 함께 사용하여 기본동작을 바꿀 수 있다.

아래 예제는 비록 name속성은 필수값이지만, age속성은 값을 주지 않아도 동작하는 예제이다. 이 예제는 직접 프로젝트를 구성해서 실행해 보자. 단지 Student.java파일만 바뀐것을 제외하면 @Required annotation예제와 아주 유사하다.

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;

public class Student {
   private Integer age;
   private String name;

   @Autowired(required=false)
   public void setAge(Integer age) {
      this.age = age;
   }
   
   public Integer getAge() {
      return age;
   }

   @Autowired
   public void setName(String name) {
      this.name = name;
   }
   
   public String getName() {
      return name;
   }
}









반응형

+ Recent posts