Backend/Spring

스프링 XML 정리 - 컨테이너(applicationContext)

leecom116 2022. 11. 14. 08:19

<bean> 태그 - 객체 생성 태그

ex) <bean id = "아이디"  class="클래스"/>

 

- id : 객체 이름, 식별자
- class : 객체를 생성할 클래스

 


<constructor-arg> 태그 - 생성자 의존 주입

ex)
  <bean id = "springDao" class="com.spring.springDao">
     <constructor-arg ref="springDao" >
  </bean>

 


<property> 태그 - 메소드 의존 주입

ex)
  <bean id = "springDao" class="com.spring.springDao">
     <property name = "userId" value = "lee"/>
      <property name = "userPwd" value = "123"/>
  </bean>

 

 

<context: annotation-config />

- 이미 등록된 빈에만 어노테이션 활성화

- @Autowired, @Qualifier만 해결 가능

- xml에 bean을 반드시 선언

 

 

<context:component-scan />
- 빈의 등록 여부와 관계 없음. 
- 스프링이 빈 스캔을 하여 어노테이션 활성화

- 모든 클래스를 스캔하고 빈 작성
  (@Autowired, @Qualifier 뿐만 아니라 @Component, @Controller, @Service, @Repository)
- base-package를 통해 스프링이 스캔할 패키지 위치를 지정 필요

 

둘의 공통점

- 의존성 주입(DI) - 스프링 IoC의 중요한 개념

- 의존성 주입은 위 과정을 통해 일어난다.


 


AbstractApplicationContext
- 컨테이너 종료(close)와 같은 기능을 제공해주는 객체

GenericXmlApplicationContext
- AbstractApplicationContext의 객체를 상속 받아 만든 클래스
- xml 파일에서 스프링 빈 설정 정보를 읽어오는 역할
ex) 

// 스프링 컨테이너 불러오기
AbstractApplicationContext context = new GenericXmlApplicationContext(
"classpath:com/anno/scope/applicationContext.xml");
// classpath : 실행할 xml 파일 경로

AnnotationConfigApplicationContext

- 자바 설정에서 정보를 읽어와 빈 객체를 생성 및 관리
- @Configuration 어노테이션이 붙은 클래스는 applicationContext.xml과 같은 역할
- 하나이상의 @Bean이 있으면 @Configuration 필요

ex)

AbstractApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

 

<context:property-placeholder>

- location 속성에 입력한 프로퍼티 파일의 정보를 불러와

  빈 설정에 입력한 placeholder의 값을 프로퍼티 파일에 존재하는 값으로 변경

- placeholder : ${로 시작하고 }로 끝나는 값

<!-- Properties 파일 로드 -->
<context:property-placeholder location="classpath:com/prop/user.properties"/>

<!-- 프로퍼티 값을 할당 -->
<bean id="userService" class="com.prop.UserServiceImpl">
    <property name="name" value="${join.name}"/>
    <property name="tel" value="${join.tel}"/>
    <property name="age" value="${join.age}"/>
</bean>