2014년 5월 21일 수요일

[SPRING]빈 등록 방법(XML편)

1.applicationContext.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- 빈 등록 방법 5가지중 XML을 사용하는 3가지 방법입니다 -->
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.        xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  6.        xmlns:context="http://www.springframework.org/schema/context"
  7.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8.                             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
  9.                             http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">
  10.         <!-- 1.bean태그를 사용하여 빈 등록 -->
  11.     <bean id="user" class="domain.User">
  12.     </bean>
  13.         <!-- 2.전용태그를 사용하여 빈 등록 -->
  14.     <jdbc:embedded-database id="embeddedDatabase" type="HSQL">
  15.     </jdbc:embedded-database>
  16.         <!-- 3.stereo type의 annotation을 사용 -->
  17.         <!-- service패키지 아래 모든 스테레오 타입을 빈으로 등록 -->
  18.     <context:component-scan base-package="service"/>
  19. </beans>
2.User.java
  1. package domain;
  2. public class User {
  3.     public void test(){
  4.         System.out.println("User test()실행");
  5.     }
  6. }
3.MyService.java
  1. package service;
  2.  
  3. import org.springframework.stereotype.Component;
  4.  
  5. @Component("myService")
  6. public class MyService {
  7.     public void test(){
  8.         System.out.println("MyService test()실행");
  9.     }
  10. }
4.BeanTagTest
  1. import javax.sql.DataSource;
  2.  
  3. import org.springframework.context.support.GenericApplicationContext;
  4. import org.springframework.context.support.GenericXmlApplicationContext;
  5.  
  6. import service.MyService;
  7. import domain.User;
  8.  
  9. public class BeanTagTest {
  10.     public static void main(String[] args){
  11.         GenericApplicationContext ac = new GenericXmlApplicationContext("applicationContext.xml");
  12.        
  13.         //1.<bean>태그 사용
  14.         User user = ac.getBean("user", User.class);
  15.         user.test();
  16.         //2.전용태그 사용
  17.         DataSource ds = ac.getBean("embeddedDatabase", DataSource.class);
  18.         System.out.println(ds);
  19.         //2.스테레오타입 애노테이션 & 전용태그 빈 스캔 사용
  20.         MyService myService = ac.getBean("myService", MyService.class);
  21.         myService.test();
  22.     }
  23. }
http://hsqldb.org/ 다운로드 후 hsqldb와sqltool jar파일을 외부라이브러리에 추가

  • XML:<bean>태그
<bean>태그를 사용한는 건 가장 단수하면서도 가장 강력한 설정 방법
  • XML:네임스페이스(스키마등록)와<bean>태그
<bean>태그 외에도 다양한 스키마에 정의된 전용 태그를 사용해 빈을 등록하는 방법
  • XML:스테레오타입 애노테이션과 빈 스캐너
XML문서와 같이 한곳에 명식적으로 선언하지 않고도 스프링 빈을 등록하는 방법

댓글 없음:

댓글 쓰기