Posts Tagged ‘Spring’

Spring Dependency Injection 정리

Tuesday, March 25th, 2008

오늘부터 아침 스터디를 시작했다. 업무 시작 1시간 전에 나와서, 30분간 각자 책을 읽거나 인터넷에서 관심있는 아티클을 읽고 나머지 30분간 각자가 배운 내용을 공유하는 방식으로 진행하기로 했다.

오늘 공부할 주제로 “Spring Dependency Injection & Java 5″ 아티클을 선택했다. 최근 Spring 관련 정보를 너무 멀리 한 것 같아서 SpringSource 팀 블로그에서 최근 글 리스트를 살펴봤고, 이 글에 끌려서 읽기 시작했다.

간단히 내용을 요약하자면, Spring에서 DI를 구현할 수 있는 3가지 방법에 대해 설명이 되어 있고 각각의 장단점에 대해 잘 설명이 되어 있다.

가장 기본적이면서 많이 쓰이고 있는 방식은 XML 설정 파일을 통해 의존성을 설정해 주는 방식이다. XML 방식은 의존성 설정 파일을 한 곳에 모아서 관리할 수 있기 때문에 코드와 설정이 분리되어 있고, 중앙에서 전체 구조를 파악하기 좋은 장점이 있으나 Type Safety 체크가 어렵고 리팩토링 친화적이지 않은 단점 때문에 다른 대안을 필요로 한다.

XML 방식에 대한 대안으로 annotation 기반으로 코드에 의존성을 선언할 수 있는 방식이 Spring 2.5에서 소개되었다. 코드에 선언된 @Autowired annotation과 @Qualifier annotation을 사용해서 의존성을 삽입할 수 있다. 이 방식은 코드와 설정 파일이 한 곳에 있어서 의존성 파악이 쉬운 장점이 있지만 반대로 의존성 설정이 코드에 흩어져 있어서 전체적인 구조 파악을 방해할 수도 있다. XML 방식보다는 Type Safety를 더 정확히 보장해 주지만 복잡한 설정은 XML을 추가로 사용해야 하는 단점이 있다.

// In file OrderServiceImpl.java:

public class OrderServiceImpl implements OrderService {
    private OrderRepository orderRepository;

    @Autowired
    public JdbcOrderServiceImpl(OrderRepository orderRepo) {
        this.orderRepository = orderRepo;
    }

    // ...
}

// In file JdbcOrderRepositoryImpl.java:

public class JdbcOrderRepositoryImpl implements OrderRepository {

    @Autowired
    @Qualifier("myDataSource")
    private DataSource orderDataSource;

    // ...
}

code from ‘Introduction to the Spring Framework 2.5′ by Rod Johnson

마지막으로 현재 개발 중에 있는 JavaConfig 방식이 있다. XML로 설정하던 설정 파일을 Plain Java 코드로 구현하는 방식으로 완벽하게 Type Safety를 보장해 주며 코드와 설정 파일을 분리시켜 주는 장점을 그대로 가지고 있는 방식이다. RubyOnRails에서 설정 파일을 Ruby 파일로 구현하는 것과 같은 방식이라 할 수 있다.

@Configuration
public class MyConfig {
   @Bean
   public Person rod() {
      return new Person("Rod Johnson");
   } 

   @Bean(scope = Scope.PROTOTYPE)
   public Book book() {
      Book book = new Book("Expert One-on-One J2EE Design and Development");
      book.setAuthor(rod());  // rod() method is actually a bean reference !
      return book;
   }
}

code from ‘A Java configuration option for Spring’ by Rod Johnson’

결론적으로 세 가지 방식을 통해 DI를 구현할 수 있기 때문에 개발자가 상황에 맞게 적절한 DI 구현 방식을 선택할 수 있는 기회가 생겼다고 할 수 있다. 기존의 XML 방식은 복잡한 구조의 대형 프로젝트에서 여전히 유용하게 사용될 수 있을 것이며, 간단한 프로젝트에서는 annotation 방식을 통해 번거로운 XML 작업 없이 프로젝트 개발이 가능해졌다. 그리고 앞으로 발표된 JavaConfig 방식은 IDE와 연동해서 리팩토링에 친화적이며 Type Safety를 보장해 주는 이점이 극대화될 수 있을 것 같다.

Spring2.0 Overviewed by fantazic

Sunday, October 8th, 2006

Spring2.0 reference (한글 번역판 / 동국씨 수고 많으셨습니다.)
Toby님의 Spring2.0 소개

Summary - 복잡한 XML 설정이 쉬워지고 확장성이 커졌다. Annotation 활용도가 높아졌고, 새로운 기술이나 경향을 적극 도입했다.

1. Spring의 가장 주요한 기능 IoC와 AOP의 변화

  • The Inversion of Control (IoC) container
  • * Easier XML configuration - XML Schema based configuration, 태그 외에 , , 등의 태그를 AOP, 트랜잭션, 다른 프레임워크와 연동 등의 구현에 사용할 수 있다.

    <!-- creates a java.util.List instance with values loaded
    from the supplied 'sourceList' -->
    <strong><util:list id="emails"></strong>
      <value>pechorin@hero.org</value>
      <value>raskolnikov@slums.org</value>
      <value>stavrogin@gov.org</value>
      <value>porfiry@gov.org</value>
    <strong></util:list></strong>
    

    * New bean scopes - singleton, prototype 외에 session, request, 사용자 정의 scope 등이 사용될 수 있다.
    * Extensible XML authoring - 사용자 Spring 태그를 구현할 수 있다. 쉽게 확장 가능하고 plugin으로 사용 가능하다.

  • Aspect Oriented Programming (AOP)
  • * Easier AOP XML configuration - POJO 기반의 bean을 AOP에서 사용 가능하다.

    <aop:config>
      <aop:aspect id="myAspect" ref="aBean">
      ...
      </aop:aspect>
    </aop:config>
    <bean id="aBean" class="...">
      ...
    </bean>
    <aop:config>
      <aop:pointcut id="businessService"
        expression="execution(* com.xyz.myapp.service.*.*(..))"/>
    </aop:config>
    <aop:aspect id="beforeExample" ref="aBean">
      <aop:before
        pointcut-ref="dataAccessOperation"
        method="doAccessCheck"/>
      ...
    </aop:aspect>
    

    * Support for @AspectJ aspects - @AspectJ annotations 를 사용할 수 있다.

    package org.xyz;
    import org.aspectj.lang.annotation.Aspect;
    @Aspect
    public class NotVeryUsefulAspect {
      …
    }
    

2. Middle Tier, Web Tier의 변화

  • Easier configuration of declarative transactions in XML
  • AspectJ와 연동되서 강력한 기능 발휘, @Transactional annotation 사용 가능

  • JPA
  • Java Persistence API 기능 강화

  • Asynchronous JMS
  • 비동기적 Java Message Service 기능 추가로 POJO 기반의 MessageListener 구현 가능

  • JDBC
  • NamedParameterJdbcTemplate(iBatis의 #memberId# 와 유사), SimpleJdbcTemplate(Java5.0 지원) 클래스 추가

  • A form tag library for Spring MVC
  • Spring MVC와 연동되는 모든 필요한 Taglib 추가

3. 새롭게 추가된 기능들

  • Dynamic language support
  • JRuby, Groovy and BeanShell로 작성된 bean을 사용할 수 있다.

    package org.springframework.scripting;
    public interface Messenger {
      String getMessage();
    }
    
    require  'java'
    include_class  'org.springframework.scripting.Messenger'
    class  RubyMessenger  <  Messenger
      def  setMessage(message)
        @@message  =  message
      end
      def  getMessage
        @@message
      end
    end
    

    And here is the Spring XML that defines an instance of the RubyMessenger JRuby bean.

    <lang:jruby id="messageService"
          script-interfaces="org.springframework.scripting.Messenger"
          script-source="classpath:RubyMessenger.rb">
      <lang:property name="message" value="Hello World!" />
    </lang:jruby>
    
  • JMX
  • Java Management Extensions 기능 추가

  • Task scheduling
  • Thread Pooling 구현, Quartz 구현에 사용

  • Java 5 (Tiger) support
  • Annotation 기능 활용, Spring2.0의 일부 기능은 Java5.0 이상에서만 작동 가능하다.