'di'에 해당되는 글 1건

  1. 2012.05.14 Spring3.0 DI AOP

Spring3.0 DI AOP

2012. 5. 14. 19:05
Spring 스프링을 간단히 말하면 엔터프라이즈 어플리케이션에서 필요로 하는 기능을 제공하느 프레임워크

* 경량 컨테이너 (EJB보다는 경량 하지만 struts같은것보단 무거움 대신기능은많음)
* DI (!중요 : 객체를 주입,넣어주는 역할, struts에서는 인터셉터설정해서 하던것을 설정만해주면 자동으로 넣어줌)
* AOP : 인터셉터보다 범위확장  (Struts2 인터셉터 => 액션의 동작의 전처리 후처리)
* POJO
* 스프링은 트랜잭션 처리를 위한 일관된 방법을 제공한다.
* 스프링은 영속성과 관련된 다양한 API를 지원한다.
* 스프링은 다양한 API에 대한 연동을 지원한다.

단점
* EJB 보단 가볍고 쉽지만 다른것들에 비해서는 어렵고 무겁다.

자바프로젝트만들기




Dependency Injection (DI) : 면접볼때 물어볼수있을정도로 중요함.

설정만으로 객체를 주입시켜줌







==================================프로젝트======================================
예제.
madvirus.spring.chap01
     Article (자바빈같은용도)
     ArticleDao (인터페이스 insert메소드)
     Main (applicationContext.xml)
     MySQLArticleDao (ArticleDao 를 구현 insert메소드 구현)
     WriteArticleService (인터페이스 write메소드)
     WriteArticleServiceImpl (WriteArticleService를 구현한 write메소드 구현)
applicationContext.xml (DI(Dependency Injection) 처리 : 객체의 외부에서 두개의 의존성있는 객체의 관계를 형성)


==================================코드======================================
예제.
madvirus.spring.chap01
     Article (자바빈같은용도)
package madvirus.spring.chap01;

public class Article {
}

     ArticleDao (인터페이스 insert메소드)
package madvirus.spring.chap01;

public interface ArticleDao {
    void insert(Article article);
}

     Main (applicationContext.xml)
package madvirus.spring.chap01;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

 public class Main {
    public static void main(String[] args){
        Resource resource =new ClassPathResource("applicationContext.xml");
        BeanFactory beanFactory = new XmlBeanFactory(resource);
        WriteArticleService articleService =  (WriteArticleService)beanFactory.getBean("writeArticleService");
       
         articleService.write(new Article());
    }       
}

     MySQLArticleDao (ArticleDao 를 구현 insert메소드 구현)
package madvirus.spring.chap01;

public class MySQLArticleDao implements ArticleDao{
   
    @Override
    public void insert(Article article){
        System.out.println("MySQLArticleDao.insert()실행");
    }   
}

     WriteArticleService (인터페이스 write메소드)
package madvirus.spring.chap01;

public interface WriteArticleService {
    void write(Article article);
}

     WriteArticleServiceImpl (WriteArticleService를 구현한 write메소드 구현)
package madvirus.spring.chap01;

public class WriteArticleServiceImpl implements WriteArticleService{
   
    private ArticleDao articleDao;
   
    //생성자
    public WriteArticleServiceImpl(ArticleDao articleDao){
        this.articleDao = articleDao;
    }
   
    @Override
    public void write(Article article) {
        System.out.println("WriteArticleServiceImpl.write() 메서드 실행");
        articleDao.insert(article);
    }
}

applicationContext.xml (DI(Dependency Injection) 처리 : 객체의 외부에서 두개의 의존성있는 객체의 관계를 형성)
<?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-3.0.xsd">

    <!-- DI(Dependency Injection) 처리 -->
    <!-- 객체의 외부에서 두개의 의존성있는 객체의 관계를 형성  -->
    <bean name="writeArticleService" class="madvirus.spring.chap01.WriteArticleServiceImpl">
        <!-- 생성자에 객체 전달 -->
        <constructor-arg>
            <!-- 생성자가  class="madvirus.spring.chap01.MySQLArticleDao" 를 받을수 있도록 등록 -->
            <ref bean="articleDao"/>
        </constructor-arg>
    </bean>
   
    <bean name="articleDao" class="madvirus.spring.chap01.MySQLArticleDao"/>
</beans>

==================================결과값======================================





AOP : struts의 인터셉터보다 규모가 커졌다. 적용범위가 넓다.

        여러부분에 걸쳐서 공통으로 사용되는 기능이 필요한 경우가 있다. 

        예를들어 로깅, 트랙잭션처리, 보안과 같은 기능을 처리






proxy : 대리객체  LogginAspect를 호출해줌



================================프로젝트====================================
예제.

madvirus.spring.chap01

     LoggingAspect (공통관심사항 실제처리할부분)

     MainForAop (실행할부분)

commonConcern.xml (공통관시사항 설정,적용)


==================================코드======================================

예제.

madvirus.spring.chap01

     LoggingAspect (공통관심사항 실제처리할부분)

package madvirus.spring.chap01;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.StopWatch;

public class LoggingAspect {

    private Log log = LogFactory.getLog(getClass());
   
    public Object logging (ProceedingJoinPoint joinPoint) throws Throwable{

        log.info("기록시작");

        StopWatch stopWatch = new StopWatch();
        try{

            stopWatch.start();
        Object retValue = joinPoint.proceed();
            return retValue;

        }catch(Throwable e) {
            throw e;
        }finally{

            stopWatch.stop();
            log.info("기록종료");
            log.info(joinPoint.getSignature().getName() + "매서드 실행시간 : " + stopWatch.getTotalTimeMillis());

        }
    }
}

     MainForAop (실행할부분)

package madvirus.spring.chap01;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainForAop {

    public static void main(String[] args){
        String[] configLocations = new String[] {"applicationContext.xml","commonConcern.xml"};
       
        ApplicationContext context = new ClassPathXmlApplicationContext(configLocations);
        WriteArticleService articleService = (WriteArticleService) context.getBean("writeArticleService");
       
        articleService.write(new Article());
    }   
}

applicationContext.xml

<?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-3.0.xsd">

    <!-- DI(Dependency Injection) 처리 -->
    <!-- 객체의 외부에서 두개의 의존성있는 객체의 관계를 형성  -->
    <bean name="writeArticleService" class="
madvirus.spring.chap01.WriteArticleServiceImpl">
        <!-- 생성자에 객체 전달 -->
        <constructor-arg>
            <!-- 생성자가  class="madvirus.spring.chap01.MySQLArticleDao" 를 받을수 있도록 등록 -->
            <ref bean="articleDao"/>
        </constructor-arg>
    </bean>
   
    <bean name="articleDao" class="madvirus.spring.chap01.MySQLArticleDao"/>
</beans>


commonConcern.xml (공통관시사항 설정,적용)

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
      
    <bean id="logging" class="madvirus.spring.chap01.LoggingAspect"/>       
    <aop:config>
        <!-- 공통관시사항 설정  -->
        <aop:pointcut id="servicePointcut" expression="execution(* *..*Service.*(..))"/>
        <!-- 공통관심사항 실제적용 -->
        <aop:aspect id="loggingAspect" ref="logging">
            <aop:around pointcut-ref="servicePointcut" method="logging" />
        </aop:aspect>
    </aop:config>
</beans>


==================================결과값======================================


'스프링3.0' 카테고리의 다른 글

스프링 3.0 @ 어노테이션 기반 설정  (0) 2012.05.14
Spring3.0 message&event  (1) 2012.05.14
Spring3.0 Di 2  (0) 2012.05.14
스프링 3.0 강좌  (0) 2012.05.11
스프링 3.0 동영상 강좌.  (0) 2012.05.09
Posted by 사라링

BLOG main image
.. by 사라링

카테고리

사라링님의 노트 (301)
JSP (31)
J-Query (41)
JAVA (24)
VM-WARE (0)
디자인패턴 (1)
스크랩 (0)
스트러츠 (3)
안드로이드 (11)
오라클 (45)
우분투-오라클 (1)
이클립스메뉴얼 (6)
스프링3.0 (23)
자바스크립트 (10)
HTML5.0 (17)
정보처리기사 (1)
기타(컴퓨터 관련) (1)
문제점 해결 (3)
프로젝트 (2)
AJAX (4)
하이버네이트 (3)
트러스트폼 (11)
Jeus (2)
재무관리(회계) (5)
정규식 (5)
아이바티스 (8)
취미 (2)
소프트웨어 보안 관련모음 (0)
정보보안기사 (6)
C언어 베이직 및 프로그램 (3)
보안 관련 용어 정리 (2)
넥사크로 (6)
Total :
Today : Yesterday :