2024.06.18

김무영·2024년 6월 20일

의존성 주입 (설정파일)

  • 생성자 의존성 주입, method 의존성주입, Factory Method 의존성 주입
    • Factory Method : 개발자가 singleton으로 클래스를 생성의존성 주입

생성자 의존성 주입

  1. 의존성 주입할 클래스 설정
    <bean id = "아이디" class = "패키지명.클래스명" scope = "singleton"/>
  2. 의존성 주입 받을 클래스를 설정하고 <constructor-arg ref=""/> 속성 정의
    <bean id = "아이디" class = "패키지명.클래스명" scope = "singleton">
    	<constructor-arg ref"의존성주입받을 객체"/>
    </bean>
  • 예 )
     1. 의존성 주입할 클래스 설정
    	<bean id="od" class="day0618.OracleDAO" scope="singleton"/>
     2. 의존성 주입 받을 클래스를 설정하고 <constructor-arg ref=""/> 속성 정의
       <bean id = "service" class = "day0618.ServiceImpl" scope = "singleton">
       <constructor-arg ref="od"/>
       </bean>
     3. Spring Container에서 얻기
       Service s = ac.getBean("service");

method 의존성 주입

  1. 의존성 주입할 클래스 설정

    <bean id = "아이디" class = "패키지명.클래스명" scope = "singleton"/>
  2. 의존성 주입 받을 클래스를 설정하고 <property name="" ref=""/> 속성 정의

    <bean id = "아이디" class = "패키지명.클래스명" scope = "singleton">
    	<property name="setter method명" ref="의존성 주입할 객체"/>
    </bean>
    // setter method명 : set을 제외한 method명을 소문자로 작성
     1. 의존성 주입받을 클래스 설정
    	public class ServiceImpl{
      	private DAO dao;
          
          public SerivceImpl(){
          
          }
      	
          public void setDao(DAO dao){
          	this.dao=dao;
          }
      
      }
     <bean id = "od" class = "day0618.OracleDAO" scope = "singleton"/>
      <bean id = "service" class = "day0618.ServiceImpl" scope = "singleton">
     	<property name="dao" ref="od"/>
     </bean>

Factory Method의존성 주입

  • singleton pattern으로 구현된 클래스를 객체화

    <bean factory-method="method명">
  • singleton pattern이 적용된 클래스

     public class ServiceImpl{
    	private static ServiceImpl si;
      
      private ServiceImpl(){
      }
      
      public static ServiceImpl getInstance(){
      return si;
      }
    
     }
  • private 접근지정자가 설정된 생성자도 호출 가능.

    <bean id = "아이디" class="패키지명.클래스명"/>
  • factory-method 호출

    <bean id = "아이디" class="패키지명.클래스명"> factory-method="getInstance"/>
    - getnInstance method가 생성하여 반환한 객체를 id로 저장하여 사용한다.

다양한 injection

  • 생성자가 객체가 아닌 다른 데이터 형을 정의하고 있을 때

  • 정수의 Injection : value속성( value="값" )과 type속성 (type="데이터형")으로 사용.

  • 사용법 )

    <bean id="" class="">
      <constructor-arg value="" type="데이터형"/>
    </bean>
    • 데이터형 : type속성을 생략하면 숫자형태 일지라도 문자열로 입력.
      예)
      문자열 : type="java.lang.String"
      숫자 : type="int", type="long", type="float", type="double"
    public class TestService{
    	private String str;
      private int value;
      
      public TestService(int value){
      	this.value=value;
      }
    	
      public TestService(String str){
      	this.str=str;
      }
    
    }
  • type속성을 기술하지 않으면 문자열로 매개변수를 받음

    <bean id="ts" class="TestService">
    	<constructor-arg value="2024"/>
    </bean>
  • 정수를 injection 하려면 type속성을 기술

    <bean id="ts" class="TestService">
    	<constructor-arg value="2024" type="int"/>
    </bean>

JCF( Java Collection Framework )Injection

  • java.util.List, Set, Map Injection

List(Set) Injection

public class Service{
private List<String> list;

public Service(List<String> list){
this.list=list;
}
}
<bean id="" class="">
	<constructor-arg>
    	<list> 또는 <set>
        <value type="데이터형"></value>
        <value type="데이터형"></value>
        </list> 또는 </set>
    </constructor-arg>
</bean>

Map Injection

public class Service{
private Map<String,String> map;

public Service(Map<String,String> map){
this.map=map;
}
}
<bean id="" class="">
	<constructor-arg>
    	<map>
        	<entry>
        		<key><value type="데이터형"></value></key>
        		<value type="데이터형"></value>
            </entry>
            .
            .
        </map>
    </constructor-arg>
</bean>

Spring DI - annotation 방식

  • 설정용 XML에 의존성 주입관계를 설정하지 않고 사용하는 방식.
    • 주입관계 : <bean>
  • 의존성 주입관계를 한눈에 파악하기 힘들다.
  • 대규모 프로젝트에는 적합하지 않고, 소규모 프로젝트에 적합한 방식.
  • Spring Context필요.
  • Spring Container가 지정된 package를 component-scan하여 클래스를 찾고 annotation이 지정된 대로 의존성 주입해준다.
  • 사용법 )
  1. Component scan의 대상이 될 클래스 (bean) 위에 @Component annotation 설정
  2. 의존성 주입받을 클래스(interface) 위에 @Autowired를 설정.

@Component

  • Spring franework에서 관리되는 bean을 설정할 때 사용.
  • annotation이 붙은 클래스는 Spring Container에서 빈으로 관리되며, 다른 클래스로 의존성주입이 될 수 있다.

@Autowired

  • 자동으로 의존성 주입을 받을 때 사용.
  • class field에 정의된 객체를 찾아 의존성 주입할 때 사용.
  • @Autowired(required=false)를 설정하여 의존성 주입을 객체가 빈으로 생성되지 않더라도 실행되어야할 때 사용.
  • Filed Injection, Constructor Injection, setter method Injection 3가지를 할 수 있다.

Field Injection (필드 주입) : 클래스의 필드에 직접 주입.

  • 예 )
    @Component
    public class Test{
    	@Autowired(required = false)
      private Temp temp;
    }

Constructor Injection (생성자 주입) : 생성자를 통해서 주입

  • 예 )
    @Component
    public class Test{
    	private Temp temp;
    	@Autowired(required =false)
      private Temp temp(Temp temp){
      	this.temp = temp
      
      }
    }

setter method Injection (세터 method 주입) : setter method로 주입

  • 예 )
    @Component
    public class Test{
    	private Temp temp;
      
    	@Autowired(required =false)
      private void setTemp(Temp temp){
      	this.temp = temp
      
      }
    }
    • 패키지명.* : 패키지내의 모든 클래스를 참조하겠다.(인식못할시)

0개의 댓글