728x90


2. 스프링 DI (빈 생성과 의존 관계 설정)  스프링 2.5 / = Study = 

2010.05.11. 17:45

복사http://blog.naver.com/chocolleto/30085911267

번역하기 전용뷰어 보기

2. 빈(Bean) 생성과 의존 관계 설정

  □ 빈 생성 및 사용
    ■ <bean>태그를 이용하여 생성할 빈 객체에 대한 정보 설정.
      ○ <bean> 태그
        - 스프링 컨테이너가 관리할 빈 객체를 생성.
 <?xml version="1.0" encoding="UTF-8"?>

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

    <bean id="articleDao" class="kame.spring.chap02.MysqlArticleDao">
    </bean>

 </beans>
      ○ <bean> 태그 속성
        - class : 생성할 빈 객체의 완전한 클래스 이름.
        - id : 스프링 컨테이너에서 생성된 객체를 구분하는데 사용되는 식별값. (name 속성을 사용해도 됨.)
    ■ 컨테이너로부터 빈 객체를 가져와 사용
 Resource resource = new ClassPathResource("applicationContext.xml");
 // 스프링 컨테이너 생성
 BeanFactory beanFactory = new XmlBeanFactory(resource);
 // 스프링 컨테이너로부터 빈 객체를 가져와 사용
 MysqlArticleDao articleDao = (MysqlArticleDao)beanFactory.getBean("articleDao");
      - 식별값(id속성 또는 name 속성)을 getBean() 메서드에 전달해서 컨테이너로부터 객체를 가져올 수 있음.
    ■ 주의 사항
      - <bean> 태그에 생성자와 관련된 정보(<constructor-arg>태그)를 명시하지 않았다면, 스프링은 파라미터가 없는 기본 생성자를
         이용하여 객체를 생성.
      - 빈으로 사용할 클래스에 파라미터를 갖는 생성자를 정의했다면 기본 생성자도 함께 정의.
 public class MysqlArticleDao implements ArticleDao {
    // 파라미터를 갖는 생성자가 정의되어 있는 경우, 기본 생성자 추가해야 함.
    public MysqlArticleDao() {}

    public MysqlArticleDao(DataSource dataSource) {
        .......
    }
 }
    ■ 빈 팩토리 메서드
      ○ 생성자가 아닌 static 메서드를 이용하여 객체를 생성해야 하는 경우.
 // 싱글톤 패턴이 적용된 클래스.
 public class ParserFactory {
    private static ParserFactory instance = new ParserFactory();

    public static ParserFactory getInstance() {
        return instance;
    }

    // 기본 생성자 접근 막음.
    private ParserFactory() {}
    .......
 }
      ○ <bean> 태그에 factory-method 속성값으로 static 메서드를 지정
        - 해당 메서드를 이용하여 빈을 생성하도록 설정.
 <bean id="parserFactory" class="kame.spring.chap02.ParserFactory"
    factory-method="getInstance" />
        - factory-method 속성을 지정하면 스프링 컨테이너는 생성자를 사용하지 않고 getInstance()메서드를 이용하여 ParserFactory
          클래스의 객체를 구함.

  □ 의존 관계 설정
    - 스프링 컨테이너에서 각 객체 간의 의존 관계도 XML 파일을 통해 명시 가능.
    ■ 생성자 방식
      - 의존하는 객체를 생성자를 통해 전달 받음.
      ○ 의존 관계
        - WriteArticleServiceImpl 클래스는 ArticleDao 인터페이스에 의존.
      ○ 생성자를 통해 의존하는 객체 전달 받기
 public class WriteArticleServiceImpl {
    private ArticleDao articleDao;

    public WriteArticleServiceImpl(ArticleDao articleDao) {
        this.articleDao = articleDao;
    }

    public void write(Article article) {
        ...
        articleDao.insert(article);
    }
 }
      ○ <constructor-arg> 태그
        ● 특징
          - 생성자를 통해서 의존하는 객체를 전달 받는 경우, <constructor-arg> 태그를 이용하여 의존하는 객체를 전달 할 수 있음.
          - 스프링은 <constructor-arg> 태그를 통해 전달된 값의 타입과 가장 근접한 파라미터를 갖는 생성자를 이용하여 객체를 생성.
        ● <constructor-arg> 태그를 이용한 생성자 방식의 설정
 <!-- WriteArticleServiceImpl 클래스의 생성자에 식별값이 "articleDao"인 빈 객체를 전달.-->
 <bean id="writeArticleService" class="kame.spring.chap02.WriteArticleServiceImpel">
    <constructor-arg>
        <ref bean="articleDao">
    </constuctor-arg>
 </bean>

 <bean id="articleDao" calss="kame.spring.chap02.OracleArticleDao">
 </bean>
 // 코드로 표현
 OracleArticleDao articleDao = new OracleArticleDao();
 WriteArticleServiceImpl writeArticleService = new WriteArticleServiceImpl(articleDao);
         - <ref> 태그는 레퍼런스(reference)를 의미.
         - <ref> 태그 대신에 <constructor-arg> 태그의 ref 속성을 사용하여 지정 가능.
 <bean id="writeArticleService" class="kame.spring.chap02.WriteArticleServiceImpel">
    <constructor-arg ref="articleDao" />
 </bean>
        ● 생성자가 전달받는 값이 기본데이터 타입이나 String 타입일 경우
          - <ref> 태그 대신에 <value> 태그를 사용하여 값을 지정.
 <bean name="monitor" class="kame.spring.chap02.SystemMonitor">
    <constructor-arg>
        <value>10</value>
    </constructor-arg>
 </bean>
         - <value> 태그 대신에 <constructor-arg> 태그의 value속성을 사용하여 지정 가능.
 <bean name="monitor" class="kame.spring.chap02.SystemMonitor">
    <constructor-arg value="10" />
 </bean>
        ● 생성자가 전달받는 파라미터가 2개 이상인 경우
          - 파라미터 개수 만큼 <constructor-arg> 태그 설정.
 <bean name="monitor" class="kame.spring.chap02.SystemMonitor">
    <constructor-arg value="10" />
    <constructor-arg ref="sender" />
 </bean>
      ○ 예제
        - 두 개의 생성자를 갖는 클래스 설정.
        ● 두 개의 생성자를 갖는 클래스
 public class JobExecutor {
    pubilc JobExecutor(Runnable run) {
        ....
    }

    public JobExecutor(Job job) {
        ....
    }
 }
        ● Job 클래스
          - Runnalbe 인터페이스를 상속받은 인터페이스.
 public interface Job extends Runnable {
    ....
 }
        ● SomeRunnable 클래스
          - Runable 인터페이스를 구현한 클래스.
 public class SomeRunnable implements Runnable {
    ....
 }
        ● 스프링 설정 파일
 <bean name="run" class="kame.SomeRunnable" />
 <bean name="job" class="kame.Job" />

 <bean name="executor1" class="kame.JobExecutor">
    <constructor-arg ref="run" />
 </bean>

 <bean name="executor2" class="kame.JobExecutor">
    <constructor-arg ref="job" />
 </bean>
         - executor1 빈을 생성할 때에는 Runnable(SomeRunnable의 타입이 Runnable이므로)을 전달받는 JobExecutor 생성자 사용.
         - executor2 빈을 생성할 때에는 Job을 전달받는 JobExecutor 생성자 사용.
      ○ 예제
        - 두 개 이상의 생성자에서 기본 데이터 타입이나 래퍼 타입을 사용하여 생성하는 클래스 설정.
        ● 세 개의 생성자를 제공하는 클래스
 public class JobExector {
    public JobExecutor(String name, int seconds) { ... }
    public JobExecutor(String name, long millis) { ... }
    public JobExecutor(String name, String seconds) { ... }
 }
        ● 스프링 설정 파일1
 <bean name="executor" class="kame.spring.chap02.JobExecutor">
    <constructor-arg>
        <value>실행기1</value>
    </constructor-arg>
    <constructor-arg>
        <value>3000</value>
    </constructor-arg>
 </bean>

         - 스프링은 기본적으로 <value>에 전달된 값을 java.lang.String 타입으로 처리.
         - 두 번째 파라미터가 String 타입인 생성자를 사용해서 객체를 생성.
         - 만약 매칭되는 파라미터 타입이 String인 생성자가 존재하지 않을 경우 <value>에 전달된 값에 따라 두 번째 파라미터가 알맞는

           데이터 타입인 int인 생성자가 사용.
        ● 스프링 설정 파일2

 <bean name="executor" class="kame.spring.chap02.JobExecutor">
    <constructor-arg>
        <value>실행기1</value>
    </constructor-arg>
    <constructor-arg>
        <value type="long">3000</value>
    </constructor-arg>
 </bean>
         - <value> 태그에 type 속성을 추가하면 직접 매칭될 파라미터의 타입을 명시 가능.
         - <value> 태그뿐만 아니라 <constructor-arg> 태그에 type속성을 추가해도 동일한 동작을 함.
    ■ 프로퍼티 설정 방식
      - setXXXX() 형태의 설정 메서드를 통해서 필요한 객체와 값을 전달 받음.
        (setXXXX() 형태의 메서드에서 프로퍼티의 이름은 XXXX가 됨.)
      ○ 설정 메서드를 통해 의존하는 객체 전달 받기
 public class WriteArticleServiceImpl implements WriteArticleService {
    private ArticleDao articleDao;

    public void setArticleDao(ArticleDao articleDao) {
        this.articleDao = articleDao;
    }
 }
      ○ <property> 태그
        - 프로퍼티에 값을 전달.
        ● <property> 태그를 이용한 프로퍼티 값 설정
 <bean name="writeArticleService" class="kame.spring.chap02.WriteArticleServiceImpl">
    <property name="articleDao">
        <ref bean="mysqlArticleDao" />
    </property>
 </bean>
          - <property> 태그에서도 <ref> 태그를 이용하여 빈 객체를 프로퍼티의 값으로 전달할 수 있음.
        ● 설정 메소드가 전달받는 값이 기본데이터 타입이나 String 타입일 경우
          - <value> 태그를 사용하여 설정.
 <bean name="lockingFailManager" class="kame.spring.chap02.PessimisticLockingFailManager">
    <property name="retryCount">
        <value>3</value>
    </property>
 </bean>
        ● 빈 객체와 기본 데이터 타입값 전달
 <bean name="monitor" class="kame.spring.chap02.SystemMonitor">
    <property name="periodTime" value="10" />
    <property name="sender" ref="smsSender" />
 </bean>
    ■ XML 네임스페이스를 이용한 프로퍼티 설정
      - XML 네임스페이스를 이용하면 <property> 태그를 사용하지 않고 좀 더 간단한 방법으로 프로퍼티의 값 설정 가능.
 <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:p="http://www.springframework.org/schema/p"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd"> 

    <bean id="monitor" class="kame.spring.chap02.SystemMonitor"
        p:periodTime="10" 
        p:sender-ref="smsSender" />

    <bean id="smsSender" class="kame.spring.chap02.SmsSender" />
 </beans>
         - 접두어 "p"를 사용하여 프로퍼티 값 설정.
         - 기본 데이터 타입 설정 : "p:프로퍼티이름" 속성을 사용하여 프로퍼티 값을 설정.
         - 빈 객체를 프로퍼티에 전달 : "p:프로퍼티이름-ref" 속성을 사용.
    ■ 임의 빈 객체 전달
      - 식별 값을 갖지 않는 빈 객체를 생성해서 전달 가능.
      - <constructor-arg> 태그나 <property> 태그에 <bean> 태그를 중첩해서 사용.
 <bean id="monitor" class="kame.spring.chap02.SystemMonitor"
     p:periodTime="10">
    <property name="sender">
        <!-- 임의 빈 객체 -->
        <bean class="kame.spring.chap02.SmsSender">
            <constructor-arg value="true" />
        </bean>
     </property>
 </bean>
         - 임의 빈 객체는 식별 값을 갖지 않기 때문에 임의 빈 객체를 재사용할 수 없음. (식별값을 준다하더라도 사용할 수 없음.)

  □ 컬렉션 타입 프로퍼티 설정
    ■ 컬렉션 타입을 입력받기 위한 스프링 태그
    ■ List 타입과 배열
      ○ 특징
        - java.util.List 타입의 프로퍼티나 생성자 인자에 값 목록을 전달.
        - <list> 태그 사용
      ○ 설정 방법
 public class ProtocolHandler {
    private List<Filter> filters;

    public void setFilters(List<Filter> filters) {
        this.filters = filters;
    }
    ......
 }
 <bean name="handler" class="kame.spring.chap02.ProtocolHandler">
    <property name="filters">
        <list>
            <ref bean="encryptionFilter" />
            <ref bean="zipFilter" />
            <bean class="kame.spring.chap02.HeaderFilter" />
        </list>
    </property>
 </bean>

 <bean name="zipFilter"class="kame.spring.chap02.ZipFilter" />
 <bean name="encryptionFilter" class="kame.spring.chap02.EncryptionFilter" />
      ○ <list> 태그
        - List에 저장된 객체 목록을 <ref> 태그를 이용하여 전달 받음.
        - <bean> 태그를 이용하여 식별 값을 갖지 않는 임의 객체를 List에 전달 가능.
      ○ List에 저장되는 값이 래퍼 타입이거나 String 타입일 경우
        - <value> 태그를 사용하여 값 전달.
        - <list> 태그의 value-type 속성을 이용하여 List에 저장될 값들의 타입 명시 가능.
        - <value> 태그에 type 속성을 이용해도 List에 저장될 값들의 타입 명시 가능.
 <bean name="monitor" class="kame.spring.chap02.PerformanceMonitor">
    <property name="deviations">
        <!-- <value> 태그에 명시된 값은 String 타입으로 처리. -->
        <list>
            <value>0.2</value>
            <value>0.3</value>
        </list>
    </property>
 </bean>
 public class PerformanceMonitor {
    private List deviations;

    public setDeviations(List deviations) {
        this.deviations = deviations;
    }
 }
 <bean name="monitor" class="kame.spring.chap02.PerformanceMonitor">
    <property name="deviations">
        <!-- value-type 속성을 이용하여 Double 타입으로 처리. -->
        <list value-type="java.lang.Double">
            <value>0.2</value>
            <value>0.3</value>
        </list>
    </property>
 </bean>
 <bean name="monitor" class="kame.spring.chap02.PerformanceMonitor">
    <property name="deviations">
        <!-- value 태그의 type 속성을 이용하여 Double 타입으로 처리. -->
        <list>
            <value type="java.lang.Double">0.2</value>
            <value type="java.lang.Double">0.3</value>
        </list>
    </property>
 </bean>
      ○ Generic 을 이용할 경우
        - <list>나 <value>태그에 값의 타입을 명시하지 않아도 알맞게 타입을 변환.
 public class PerformanceMonitor {
    private List<Double> deviations;

    public setDeviations(List<Double> deviations) {
        this.deviations = deviations;
    }
 }
 <bean name="monitor" class="kame.spring.chap02.PerformanceMonitor">
    <property name="deviations">
        <!-- 제너릭을 사용한 경우, 알맞게 타입 처리. -->
        <list>
            <value>0.2</value>
            <value>0.3</value>
        </list>
    </property>
 </bean>
      ○ List에 저장될 값을 표현하기 위해 사용 가능한 태그
        - <ref> : 다른 스프링 빈 객체를 값으로 사용.
        - <bean> : 임의 빈 객체를 생성해서 값으로 사용.
        - <value> : 래퍼 타입이나 String을 값으로 사용.
        - <list>, <map>, <props>, <set> : 컬렉션 객체를 값으로 사용.
        - <null> : null 값을 값으로 사용.
      ○ 배열
        - <list> 태그는 배열을 설정할 때도 사용.
 public class ProtocolHandler {
    private Filter[] filters;

    public void setFilters(Filter[] filters) {
        this.filters = filters;
    }
    ......
 }
        - <list> 프로퍼티를 이용해서 값 전달.
    ■ Map 타입
      ○ 특징
        - java.util.Map 타입의 프로퍼티를 설정.
        - <map> 태그 사용.
      ○ 설정 방법
 public class ProtocolHandlerFactory {
    private Map<String, ProtocolHandler> handlers;

    public void setHandlers(Map<String, ProtocolHandler> handlers) {
        this.handlers = handlers;
    }
    .......
 }
 <bean name="handlerFactory" class="kame.spring.chap02.ProtocolHandlerFactory">
    <property name="handlers">
        <map>
            <entry>
                <key><value>soap</value></kay>
                <ref bean="soapHandler" />
            </entry>
            <entry>
                <kay><value>rest</value></kay>
                <ref bean ="restHandler" />
            </entry>
        </map>
    </property>
 </bean>
      ○ <entry> 태그
        - 한 개의 <entry> 태그는 Map에 저장될 한 개의 <키, 값>을 표현.
        - 두 개의 자식 노드를 가지며, 각각 키와 값을 의미.
 <map>
    <entry>
        <kay><키태그>...</키태그></key>
        <값태그>...</값태그>
    </entry>
 </map>
        ● <키태그>와 <값태그>에 지정할 수 있는 태그
          - <ref> : 다른 스프링 빈 객체를 키로 사용.
          - <bean> : 임의 빈 객체를 생성해서 키로 사용.
          - <value> : 래퍼 타입이나 String을 키로 사용.
          - <list>, <map>, <props>, <set> : 컬렉션 객체를 키로 사용.
          - <null> : null 값을 키로 사용.
      ○ 예제
 <map>
    <!-- 키와 값의 타입이 각각 String과 Integer일 경우 지정.-->
    <entry>
        <key><value>1</value></key>
        <value type="java.lang.Integer">1th</value>
    </entry>
    <!-- 빈 객체를 참조할 경우 <ref> 태그를 이용하여 지정. -->
    <entry>
        <key><ref bean="protocol"></key>
        <ref bean="handler" />
    </entry>
 </map>
      ○ <entry> 태그의 속성을 이용하여 표현
        - key, key-ref, value, value-ref 속성을 이용하여 <키, 값> 쌍을 좀 더 간단히 표현.
 <!-- 위 코드와 동일 -->
 <map>
    <entry key="1" value="1th" />
    <entry key-ref="protocol" value-ref="handler" />
 </map>
        - 래퍼 타입이나 String 타입을 키나 값에 할당할 때에는 key 속성과 value 속성을 사용.
        - 빈 객체를 참조할 때에는 key-ref나 value-ref를 사용하여 설정.
      ○ 제러닉을 사용하지 않은 상태에서의 래퍼 타입의 키나 값 설정
        - key-type 속성과 value-ref 속성을 이용하여 키와 값의 타입을 지정.
 <property name="ratio">
    <map key-type="java.lang.Integer" value-type="java.lang.Double">
        <entry ... />
        ......
    </map>
 </property>
    ■ Properties 타입
      ○ 특징
        - java.util.Properties 타입의 프로퍼티 설정.
          (Properties 클래스는 환경변수나 설정 정보와 같이 상황에 따라 변경 되는 값을 저장하기 위한 용도로 사용.)
        - <props> 태그 이용.
      ○ 설정 방법
 <bean name="client" class="kame.spring.chap02.BookClient">
    <property name="config">
        <props>
            <prop key="servier">192.168.1.100</prop>
            <prop key="connectionTimeout">5000</prop>
        </props>
    </property>
 </bean>
         - 프로퍼티 이름 : "server"와 "connectionTimeout"
         - 프로퍼티의 값 : "192.168.1.100"과 ."5000"
      ○ <prop> 태그
        - 한 개의 프로퍼티를 표현.
        - 프로퍼티의 이름은 key 속성을이용하여 입력.
        - 프로퍼티의 값은 <prop>태그의 몸체 내용을 이용하여 입력.
        - 한 개의 <prop> 태그는 Properties 태그에 한 개의 프로퍼티로 저장.
          (Properties.getProperty(String name)메서드를 이용하여 프로퍼티 값을 사용.)
 public class BookClient {
    private Properties config;

    public void setConfig(Properties config) {
        this.config = config;
    }

    public void connect() {
        String serverIp = config.getProperty("servier");
        ......
    }
 }
    ■ Set 타입
      ○ 특징
        - java.util.Set 타입의 프로퍼티를 설정.
        - <set>태그를 이용.
      ○ 설정방법
 <property name="subset">
    <set value-type="java.lang.Integer">
        <value>10</value>
        <value>20</value>
        <value>30</value>
    </set>
 </property>
      ○ <set> 태그
        - 집합에 저장될 값을 <value> 태그나 <ref> 등의 태그를 이용하여 표시.
        - 래퍼 타입인 경우 <list>나 <map>의 경우처럼 value-type 속성을 이용하여 저장될 값의 타입을 명시.
          (<value>태그의 type 속성도 이용 가능.)
        ● 값을 지정할 수 있는 태그
          - <ref> :  다른 스프링 빈 객체를 값으로 사용.
          - <bean> : 임의 빈 객체를 생성해서 값으로 사용.
          - <value> : 래퍼 타입이나 String을 값으로 사용.
          - <list>, <map>, <props>, <set> : 컬렉션 객체를 값으로 사용.
          - <null> : null 값을 값으로 사용.

  □ 의존 관계 자동 설정
    ■ 빈 객체 간의 의존 관계 설정
      - <property> 태그를 이용하여 설정.
 <bean name="writeArticleService" class="kame.spring.chap02.WriteArticleServiceImpl">
    <property name="articleDao">
        <ref bean="articleDao" />
    </property>
 </bean>

 <bean name="articleDao" class="kame.spring.chap02.MysqlArticleDao">
 </bean>
         - writeArticleService 빈 객체에서 articleDao 객체로의 하나의 의존 관계만을 포함.
    ■ 의존관계 자동 설정
      - 의존하는 빈 객체의 타입이나 이름을 이용하여 의존 객체를 자동으로 설정할 수 있는 기능 제공.
        (설정 파일의 크기를 줄일 수 있음.)
      - 자동 설정과 관련하여 별도의 설정을 하지 않으면 자동 설정을 사용하지 않게 됨.
      ○ 자동설정 방식
      ○ 특정 방식을 이용하여 의존 객체 설정
        - <bean> 태그에 autowire 속성을 값을 알맞게 지정.
 <bean id="monitor" class="kame.spring.chap02.SystemMonitor" autowire="byName" />
        ● autowire 속성
          - 기본 값 : default (default-autowire 속성의 값을 사용.)
      ○ 설정 파일에 포함된 모든 빈 객체에 대해서 특정 방식의 자동 설정 적용
        - <beans> 태그의 default-autowire 속성의 값에 설정 방식을 지정.
 <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
     default-autowire="byName">
    ....
 </beans>
        ● default-autowire 속성
          - 기본 값 : no (자동 설정 하지 않음.)
    ■ 프로퍼티 이름을 이용한 의존 관계 자동 설정
      ○ 특징
        - byName 방식.
        - 프로퍼티 이름과 동일한 이름을 갖는 빈 객체를 프로퍼티 값으로 설정.
      ○ 설정 방법
 <bean name="writeArticleService" class="kame.spring.chap02.WriteArticleServiceImpl
     autowire="byName" />

 <bean name="articleDao" class="kame.spring.chap02.MysqlArticleDao" />
 <bean name="mysqlArticleDao" class="kame.spring.chap02.MysqlArticleDao" />
         - WriteArticleServiceImpl 클래스가 이름이 "articleDao"인 프로퍼티를 갖고 있다면, 이름이 "articleDao"인 빈 객체가 프로퍼티의
           값으로 전달됨.
      ○ 단점
        - 코드를 리팩토링해서 프로퍼티의 이름을 변경하는 경우 기존에 올바르게 동작하던 설정 파일이 올바르게 동작하지 않을 수도
          있음.
    ■ 프로퍼티 타입을 이용한 의존 관계 자동 설정
      ○ 특징
        - byType 방식.
        - 프로퍼티의 타입과 동일한 타입을 갖는 빈 객체를 프로퍼티 값으로 설정.
      ○ 설정 방법
 <bean name="writeArticleService" class="kame.spring.chap02.WriteArticleServiceImpl"
     autowire="byType" />

 <bean name="mysqlArticleDao" class="kame.spring.chap02.MysqlArticleDao" />
         - articleDao 프로퍼티에 알맞은 빈 객체 설정.
      ○ 단점
        - 프로퍼티 타입과 동일한 타입의 빈 객체를 오직 1개만 설정 가능. 
          (동일한 타입의 빈 객체가 두 개 이상 존재하게 되면 스프링은 어떤 빈 객체를 사용해야 할 지 알 수 없기 때문에 예외 발생.)
    ■ 생성자 파라미터 타입을 이용한 의존 관계 자동 설정
      ○ 특징
        - constructor 방식.
        - byType 방식처럼 타입을 이용하여 값을 전달. (차이점 : 프로퍼티가 아닌 생성자의 파라미터 타입 사용.)
      ○ 설정 방법
 public class WriteArticleSerivceImpl {
    public WriteArticleServiceImpl(ArticleDao articleDao) {
        .........
    }
 }
 <bean name="writeArticleService" class="kame.spring.chap02.WriteArticleServiceImpl"
     autowire="constructor" />

 <bean name="mysqlArticleDao" class="kame.spring.chap02.MysqlArticleDao" />

         - WriteArticleServiceImpl(ArticleDao articleDao) 생성자의 첫 번째 파라미터에 ArticleDao 타입인 mysqlArticleDao 빈 객체가

           전달됨.
      ○ 단점
        - 생성자 파라미터 타입과 일치하는 빈 객체가 2개 이상 존재할 경우 빈 객체를 생성할 때 예외를 발생시킴.
    ■ 생성자 및 프로퍼티 타입을 이용한 자동 설정
      ○ 특징
        - autodetect 방식.
        - constructor 방식을 먼저 적용하고, constructor 방식을 적용할 수 없는 경우 byType 방식을 적용하여 의존 객체를 설정.
      ○ 설정 방법

 <bean name="writeArticleService" class="kame.spring.chap02.WriteArticleServiceImpl"
     autowire="autodetect" />

 <bean name="mysqlArticleDao" class="kame.spring.chap02.MysqlArticleDao" />
      ○ 단점
        - constructor 방식과 byType 방식을 사용하므로, 동일한 타입의 빈 객체를 2개 이상 정의 할 수 없음.
    ■ 자동 설정과 직접 설정의 혼합
      ○ 특징
        - 자동 설정과 함께 <property> 태그를 이용하여 해당 프로퍼티의 값을 직접 설정.
      ○ 설정 방법
 <bean name="writeArticleService" class="kame.spring.chap02.WriteArticleServiceImpl"
     autowire="byName">
    <property name="eventListener" ref="emailAdaptor" />
 </bean>
      ○ 특정 프로퍼티의 값이 자동 설정에 의해 초기화되지 않게 할 경우
        - <null> 태그를 이용하여 프로퍼티의 값을 null로 설정.
 <bean name="writeArticleService" class="kame.spring.chap02.WriteArticleServiceImpl"
     autowire="byName">
    <property name="eventListener"><null/></property>
 </bean>


  □ 부모 빈을 통한 설정 재사용
    - 중복되는 설정을 갖는 빈이 다수 존재할 경우, 중복되는 설정 정보를 담고 있는 부모 빈을 정의한 뒤, 부모 빈 정보를 재사용하도록

      설정.
    ■ 설정 재사용 전

 <bean id="doorMonitor" class="kame.spring.chap02.SystemMonitor">
    <property name="periodTime" value="10" />
    <property name="sender" ref="smsSender" />
 </bean>

 <bean id="lobbyMonitor" class="kame.spirng.chap02.SystemMonitor">
    <property name="periodTime" value="10" />
    <property name="sender" ref="smsSender" />
 </bean>

 <bean id="roomMonitor" class="kame.spring.chap02.SystemMonitor">
    <property name="periodTime" value="20" />
    <property name="sender" ref="smsSender" />
 </bean>
         - 빈의 이름만 다를 뿐 나머지 설정은 대부분 동일.
    ■ 부모 빈으로부터 설정 정보 상속
 <bean id="commonMonitor" class="kame.spring.chap02.SystemMonitor"
     abstract="true">
    <property name="periodTime" value="10" />
    <property name="sender" ref="smsSender" />
 </bean>

 <bean id="doorMonitor" parent="commonMonitor" />
 <bean id="lobbyMonitor" parent="commonMonitor" />
 <bean id="roomMonitor" parent="commonMonitor">
    <property name="periodTime" value="20" />
 </bean>

      ○ commonMonitor 빈
        - 빈 클래스를 비롯하여 프로퍼티 설정 등이 포함.
        - abstract="true" : 해당 빈 객체를 생성하지 않음.
        - 설정 정보만 존재할 뿐 실제로 객체는 생성되지 않음.
      ○ 자식 빈
        - parent 속성을 사용하여 클래스 및 프로퍼티 설정 정보를 물려받을 부모빈을 설정.
        - parent 속성을 이용하여 물려받은 설정 정보 중에서 변경하고 싶은 값이 있다면 추가로 입력.
        - 프로퍼티뿐만 아니라 클래스도 새롭게 지정 가능.
    ■ 자식 빈에 class 속성 이용하여 클래스 새롭게 지정
      - class 속성 이용하여 클래스를 새롭게 지정하면 부모 빈에서 설정한 클래스가 아닌 class 속성에 명시한 클래스를 사용하여 빈을

        생성.

 <bean id="commonMonitor" class="kame.spring.chap02.SystemMonitor"
     abstract="true">
    <property name="periodTime" value="10" />
    <property name="sender" ref="smsSender" />
 </bean>

 <!-- commonMonitor 빈의 프로퍼티 정보를 사용. -->
 <bean id="extMonitor" parent="commonMonitor" class="ExtendedSystemMonitor">
    <property name="defaultResolution" value="high" />
 </bean>
 <!-- 위와 동일 -->
 <bean id="extMonitor" class="ExtendedSystemMonitor">
    <property name="periodTime" value="10" />
    <property name="sender" ref="smsSender" />
    <property name="defaultResolution" value="high" />
 </bean>


728x90

'프로그래밍 > java' 카테고리의 다른 글

poi cell Number 포맷 문자로 읽기  (0) 2016.11.04
에러코드 정리  (0) 2016.05.25
에자일 방법론  (0) 2016.03.29
java.lang.UnsupportedClassVersionError  (0) 2016.03.28
java 윤년, 평년 구분하기  (0) 2016.01.18
728x90

 

에자일 방법론은 다음의 4가지 선언에서 시작되었다고 한다.

1. 프로세스나 툴 보다는 멤버간의 교류를 소중히 여길 것.

2. 포괄적인 문서에 힘을 쏟기 보다는 동작하는 소프트웨어의 개발에 힘을 기울일 것.

3. 계약의 협상보다는 고객과의 협력을 중시할 것.

4. 계획에 따르기 보다는 변화에 유연하게 대응할 것.

728x90

'프로그래밍 > java' 카테고리의 다른 글

에러코드 정리  (0) 2016.05.25
스프링 DI  (0) 2016.03.29
java.lang.UnsupportedClassVersionError  (0) 2016.03.28
java 윤년, 평년 구분하기  (0) 2016.01.18
마이바티스 메뉴얼  (0) 2015.08.26
728x90

java.lang.UnsupportedClassVersionError 

(Unsupported major.minor version 49.0)  <- 이거 중요하다. 잘 외워두자

이 에러는 자바의 컴파일 버전이 충돌이 나서이다.
하위버전의 클래스파일을 상위버전이 읽어들일때는 상관없지만 
상위버전의 클래스파일을 하위버전이 읽어올때는 위와 같은 에러를 낸다

< 에러 상세코드 >
version 50.0   컴파일 버전 : 1.6 
version 49.0   컴파일 버전 : 1.5
version 48.0   컴파일 버전 : 1.4

해결책>>

내텀퓨터 ->속성 -> 고급-> 환경변수에서 자바의 버전을 알맞게 셋팅한다. 
즉... 상위 버전에서 컴파일된 파일들은 모두 자신이 현재 쓸려고 하는 하위버전대로 다시 컴파일 하여야 한다.


진짜 해결>>

컴파일시 발생하는 Unsupported major.minor version 49.0 에러 원인 

Unsupported major.minor version 49.0 에러 딱보니 버전문제다.
JRE 라이브러리 버젼을 통일시켜 주었는데도 안된다.
뭐가 문제냐!! 바로 컴파일시 JDK버젼이 문제였다.
프로젝트 프로퍼티에서 Java Compiler탭에서 Compiler compliance level을 설정을 변경해주자

이상 끝~
컴파일러의 jre 버전이 5.0 인데 웹서버 (톰켓)의 jre 버전이 1.4이거나 낮은 버전일 경우 다음과 같은 에러가 발생한다


참조] http://mars0717.egloos.com/1061030



728x90

'프로그래밍 > java' 카테고리의 다른 글

스프링 DI  (0) 2016.03.29
에자일 방법론  (0) 2016.03.29
java 윤년, 평년 구분하기  (0) 2016.01.18
마이바티스 메뉴얼  (0) 2015.08.26
spring unchecked warning 발생 시 대처 법  (0) 2015.08.05
728x90

jQuery 자식 팝업 창에서 부모창 컨트롤


$(opener.document).find("#Form").attr("action","index.do").submit();

자식창 -> 부모창으로 값 전달하기


-opener.document.getElementById("id").value="value"; //dom 객체로 제어

$("#id",opener.document).val("value"); // jQuery 방식 1

$("input[name=imgFile]", parent.document.body).val() // 방식 2

$(opener.document).find("#id").val("value"); //방식 3

 

- opener.location.href="javascript:fun();"; //일반적인 방법

$(opener.location).attr("href","javascript:fun();"); //jQuery 이용

출처 : http://jp1020.tistory.com/

728x90

'프로그래밍 > 자바스크립트' 카테고리의 다른 글

자바스크립트 event.keyCode  (0) 2016.04.26
jQuery selectBox 제어  (0) 2016.04.14
jquery radio, select, checkbox  (0) 2013.10.28
정규 표현식 요약  (0) 2013.10.02
quick menu 바  (0) 2013.07.19
728x90

잠겨있는 계정을 언락 시켜준다.

 

SQL>ALTER USER HR ACCOUNT UNLOCK;

 

계정의 비밀번호 재 설정

 

SQL>ALTER USER HR IDENTIFIED BY a1234; (HR 계정의 비밀번호를 HR로 변경하였습니다.)

728x90

'프로그래밍 > Oracle' 카테고리의 다른 글

오라클 테이블스페이스 생성  (0) 2019.04.04
오라클 분석함수  (0) 2016.05.04
ORACLE PLS-553 오류 처리  (0) 2015.04.29
오라클 백업  (0) 2015.04.24
오라클 테이블 정보 보기  (0) 2015.04.23
728x90

GregorianCalendar gc = new GregorianCalendar();

int year = gc.get(Calendar.YEAR);

// 윤년 or 평년 : true -> 윤년 , false -> 평년

String resYmd = gc.isLeapYear(year) ? "윤년" : "평년";

System.out.printf("%d 년도는 %s 입니다.", year, resYmd);


728x90

'프로그래밍 > java' 카테고리의 다른 글

에자일 방법론  (0) 2016.03.29
java.lang.UnsupportedClassVersionError  (0) 2016.03.28
마이바티스 메뉴얼  (0) 2015.08.26
spring unchecked warning 발생 시 대처 법  (0) 2015.08.05
Java 정규식  (0) 2015.07.24
728x90

기본지식

 

IDE0 HDD : /dev/hda 로 인식됨,  디스크내의 파티션은 hda1 / hda2 / hda3 .....

IDE1 HDD : /dev/hdb 로 인식됨, 디스크내의 파티션은 hdb1 / hdb2 /hdb3....

 

하드디스크 추가하고 리눅스 부팅후...

 

1. fdisk -l 로 디스크가 추가된 것을 확인 할 수 있다.

 

[root@localhost ~]# fdisk -l

Disk /dev/hda: 20.0 GB, 20060651520 bytes
255 heads, 63 sectors/track, 2438 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device Boot      Start         End      Blocks   Id  System
/dev/hda1   *           1          13      104391   83  Linux
/dev/hda2              14        2438    19478812+  8e  Linux LVM

Disk /dev/hdb: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device Boot      Start         End      Blocks   Id  System
/dev/hdb1               1       19457   156288321    7  HPFS/NTFS      <- 추가된 hdd
[root@localhost ~]#

 

 

2. fdisk로 파티션 설정하기


[root@localhost ~]# fdisk /dev/hdb

The number of cylinders for this disk is set to 19457.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
   (e.g., DOS FDISK, OS/2 FDISK)

Command (m for help): p

Disk /dev/hdb: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device Boot      Start         End      Blocks   Id  System
/dev/hdb1               1       19457   156288321    7  HPFS/NTFS

Command (m for help): m
Command action
   a   toggle a bootable flag
   b   edit bsd disklabel
   c   toggle the dos compatibility flag
   d   delete a partition
   l   list known partition types
   m   print this menu
   n   add a new partition
   o   create a new empty DOS partition table
   p   print the partition table
   q   quit without saving changes
   s   create a new empty Sun disklabel
   t   change a partition's system id
   u   change display/entry units
   v   verify the partition table
   w   write table to disk and exit
   x   extra functionality (experts only)

Command (m for help): d     <- 파티션 삭제
Selected partition 1

Command (m for help): p

Disk /dev/hdb: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device Boot      Start         End      Blocks   Id  System

Command (m for help): n     <- 파티션 추가
Command action
   e   extended
   p   primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-19457, default 1):
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-19457, default 19457):
Using default value 19457

Command (m for help): p

Disk /dev/hdb: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device Boot      Start         End      Blocks   Id  System
/dev/hdb1               1       19457   156288321   83  Linux

 

Command (m for help): v
5165 unallocated sectors

Command (m for help): w  <- 저장하고 종료
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

 

3. 디스크 format : mkfs

 

[root@localhost home]# mkfs
Usage: mkfs [-V] [-t fstype] [fs-options] device [size]
[root@localhost ~]# mkfs.ext3 /dev/hdb1
mke2fs 1.35 (28-Feb-2004)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
19546112 inodes, 39072080 blocks
1953604 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=41943040
1193 block groups
32768 blocks per group, 32768 fragments per group
16384 inodes per group
Superblock backups stored on blocks:
        32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
        4096000, 7962624, 11239424, 20480000, 23887872

Writing inode tables: done
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 32 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.
[root@localhost ~]#


 

3. mount 하기

 

먼저 mount할 디렉토리를 만든다

mkdir /home/music

 

/dev/hdb1을 /home/music 에 마운트 한다.

mount /dev/hdb1 /home/music

 

4. /etc/fstab 내용 추가 ( 리부팅후에도 적용되도록)

 

#vi /etc/fstab

/dev/VolGroup00/LogVol00 /                       ext3    defaults        1 1
LABEL=/boot             /boot                   ext3    defaults        1 2
none                    /dev/pts                devpts  gid=5,mode=620  0 0
none                    /dev/shm                tmpfs   defaults        0 0
none                    /proc                   proc    defaults        0 0
none                    /sys                    sysfs   defaults        0 0
/dev/VolGroup00/LogVol01 swap                    swap    defaults        0 0
/dev/hdb1               /home/music             ext3    defaults        1 1    <- 추가된 내용

Posted by 네이허


728x90

'프로그래밍 > 리눅스' 카테고리의 다른 글

특정 IP만 ssh 접속 허용하기  (0) 2019.05.21
GREP 활용  (0) 2019.04.24
apache server 버전 확인  (0) 2015.09.14
리눅스 언어 설정  (0) 2015.07.24
httpd: apr_sockaddr_info_get() failed  (0) 2015.04.27
728x90

USER AGENT TOKEN WHAT IS MY USER AGENT


User Agent Analyser


Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MASMJS; rv:11.0) like Gecko



 

User Agent Fragments and Token


Mozilla/5.0 : 


"Mozilla" formerly was the codename of the Netscape Navigator and is currently used by the most browsers. The version 5 of the Netscape Navigator was the last, unreleased version, before the switch to the successor Mozilla Firefox. You will find the Mozilla/5.0 token on the most modern browser.


Windows NT 6.3 :


Windows NT 6.3 is the platform token, used by Microsoft Windows 8.1.


WOW64 :


WOW64 means, a 32-bit Microsoft Windows is running on a 64-bit processor.


Trident/7.0 :


Trident/7.0 is the identifier for the Microsoft Trident-HTML-Rendering-Engine. Version 7 currently identifies all Internet Explorer 11 versions.


MASMJS :


MASMJS is an OEM identifier and means, that this user agent is used on a Samsung device.


Fore more OEM identifier see our Windows OEM Manufacturer List.


rv:11.0 :


rv:11.0 is a revision number.


like :


Behaves like Gecko, Googlebot or other. See next token for more informations.


Gecko :


Gecko is the open source browser engine designed to support open Internet standards and is uses in several browsers like Firefox, SeaMonkey and other.

728x90

'프로그래밍 > 모바일앱' 카테고리의 다른 글

익스플로러에서 sencha touch 사용하기  (0) 2012.07.04

+ Recent posts