본문 바로가기

카테고리 없음

Spring 2.5 AOP with Web example

웹이 아닌 애플리케이션에서 AOP를 사용했던 방식 그대로 적용하면 된다. 다만, 이용자의 요청에 의해서 실행되는 콘트롤러에서 핵심기능을 호출할 수 있도록 핵심기능을 콘트롤러 안으로 주입(Dependency Injection)해 주어야 한다.

필요한 라이브러리 들




WEB-INF/dispatcher-servlet.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"
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
 
<bean name="/hello.htm"
 class="controller.HelloController" p:myBean-ref="myBean"/>
 
<bean id="aspectBean" class="aspect.MyAspect"/> <!-- 공통관심사항-->

<aop:config>
     <aop:aspect id="myAspect" ref="aspectBean">
       <aop:before pointcut="execution(* print*(..))" method="beforeprinteMessage" />
       <aop:after-returning pointcut="execution(* print*(..))" method="afterprintMessage" />
     </aop:aspect>
</aop:config>

<bean name="myBean" class="bean.MyBean"/> <!--핵심기능-->

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/" />
 <property name="suffix" value=".jsp" />       
</bean>

</beans>


controller.HelloController

package controller;
import bean.MyBean;

import javax.servlet.http.*;

import org.springframework.web.servlet.*;
import org.springframework.web.servlet.mvc.*;

public class HelloController extends AbstractController {
 
 /* Dependency Injection 을 이용하여 주입될 객체, Core concerns */
 private MyBean myBean;

 /* Dependency Injection 에 사용될 setter */
 public void setMyBean(MyBean myBean) {
  this.myBean = myBean;
 }

 @Override
 public ModelAndView handleRequestInternal(HttpServletRequest arg0,
   HttpServletResponse arg1) throws Exception {
 
  myBean.printMsg(); //핵심기능 수행
 
  ModelAndView mav = new ModelAndView();
  mav.setViewName("hello");
  mav.addObject("greeting", "감사해요, Spring2.5");
  return mav;
 }

}


WebContent/hello.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>hello.jsp</title>
</head>
<body>
<%=request.getAttribute("greeting") %><br></br>
</body>
</html>


bean.MyBean(Core concerns)

package bean;

public class MyBean {
 
 public void printMsg(){
   System.out.println("핵심기능 실행됨");
 }
}


aspect.MyAspect (공통관심사항을 포함하는 클래스)

package aspect;

public class MyAspect {
 
 /* 핵심관심사항이 실행되기 전에 실행될 공통관심사항 */
 public void beforeprinteMessage() {
  System.out.println("핵심관심사항 전에 실행됨");
 }

 /* 핵심관심사항이 실행되고 메소드가 리턴한 후에 실행될 공통관심사항 */
 public void afterprintMessage() {
  System.out.println("핵심관심사항 후에 실행됨");
 }
}