[Spring] @Autowired의 Before/After

Posted at 2009/04/29 15:35// Posted in 나만의 작업/Spring

Spring framework 2.5에 추가된 @Autowired annotation에 관한 글을 보고 정리.

알고있는 내용이기에~ 그냥 가볍게 Before 와 After code

Before - @Autowired annotation이 없었을 때 

applicationContext.xml에서 설정
<bean id="empDao" class="EmpDao" /> <bean id="empManager" class="EmpManager"> <property name="empDao" ref="empDao" /> </bean>

EmpDao의 bean을 inject
public class EmpManager { private EmpDao empDao; public EmpDao getEmpDao() { return empDao; } public void setEmpDao(EmpDao empDao) { this.empDao = empDao; } ... }

이랬던 코드가~ 바뀐다. 

After

applicationContext.xml에서 설정

<context:annotation-config /> <!-- 요거 꼭 빼먹지 말것 --> <bean id="empManager" class="autowiredexample.EmpManager" /> <bean id="empDao" class="autowiredexample.EmpDao" />

import org.springframework.beans.factory.annotation.Autowired; public class EmpManager { @Autowired private EmpDao empDao; }

Annotation을 써서 훨씬 보기에 간결한 코드를 짤 수 있다.









  1. [NC]...YellOw
    2009/04/29 22:13 [Edit/Del] [Reply]
    인자 저도 스프링 공부해야하는데 요기서 많은 도움을 얻을 수 있을거 같네요!!

댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret

스프링에서 벨로시티 뷰 템플릿 엔진을 사용하고 있는데 여기에 편리한 tools를 사용하기 위해서
필요한 설정을 기억하기 위해 기록합니다.

VelocityTools는 벨로시티 템플릿에서 숫자나 날짜, url등의 포맷팅을 지원하는 툴이고,
VelocityTools프로젝트에는 GenericTools, VelocityView, VelocityStruts 세개의 부분으로 나눠져 있습니다.

보통 GenericTools를 많이 쓸일이 많기 때문에~ 조금 정리해보면,

Generic Tools에는,

DateTool
A tool for manipulating and formatting dates.
MathTool
A tool for performing floating point math.
NumberTool
A tool for formatting numbers.
RenderTool
A tool to evaluate and render arbitrary strings of VTL (Velocity Template Language).
EscapeTool
A tool to help with common escaping needs in Velocity templates.
ResourceTool
A tool to simplify access to ResourceBundles for internationalization or other dynamic content needs.
Alternator and AlternatorTool
Utility class for easily alternating over values in a list and tool for easy creation of Alternators in templates.
ValueParser
A tool to retrieve and parse String values pulled from a map. This provides the basis for the ParameterParser in VelocityView.
ListTool
A tool to help when working with arrays or Lists. This tool transparently handles both the same way.
SortTool
A tool that allows a user to sort a collection (or array, iterator, etc) on any arbitary set of properties exposed by the objects contained within the collection.
IteratorTool
A convenience tool to use with #foreach loops. It wraps a list to let the designer specify a condition to terminate the loop, and reuse the same list in different loops.



EscapeTool
- It provides methods to escape outputs for Java, JavaScript, HTML, HTTP, XML and SQL. Also provides methods to render VTL characters that otherwise needs escaping.
을 이용하여 테스트 해보면...

toolbox.xml 파일을 하나 만들어서
<?xml version="1.0"?>
<toolbox>
 <tool>
  <key>esc</key>
  <scope>application</scope>
  <class>org.apache.velocity.tools.generic.EscapeTool</class>
 </tool>
</toolbox>

genericTool의 EscapeTool을 사용하는데 velocity에서 esc라는 키워드를 이용해서 쓰겠다~


스프링에서 Properties파일을 따로 정의했다고 하면(따로 빼 놓았다면)
# velocityViewResolver
velocity.resourceLoaderPath=/WEB-INF/velocity/
velocity.toolboxConfigLocation=/WEB-INF/spring/toolbox.xml
velocity.properties=/WEB-INF/spring/velocity.properties
velocity.overrideLogging=false
velocity.cache=false
velocity.prefix=
velocity.suffix=.vm


스프링의 설정파일에서

<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
 <property name="cache" value="${velocity.cache}" />
 <property name="prefix" value="${velocity.prefix}" />
 <property name="suffix" value="${velocity.suffix}" />
 <property name="toolboxConfigLocation" value="${velocity.toolboxConfigLocation}" />
 <property name="exposeSpringMacroHelpers" value="true" />
</bean>


.vm라는 확장자의 velocity파일에서
$esc.xml("< >")


결과는
< >



참고 :

[Velocity] 스프링 프레임워크에서 사용하기

http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/EscapeTool.html
http://forum.springframework.org/archive/index.php/t-10926.html




  1. seattle
    2008/03/20 10:56 [Edit/Del] [Reply]
    좋은정보 감사합니다. :-)

댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret

스프링 MVC를 이용한 웹 요청 처리



구성요소

DispatcherServlet : 클라이언트의 요청을 전달받음. 컨트롤러에게 클라이언트의 요청을 전달하고 컨트롤러가 리턴한 결과 값을 view에 전달하여 알맞은 응답을 생성하도록 한다.

HandlerMapping : 클라이언트의 요청 URL을 어떤 컨트롤러가 처리할 지를 결정

Controller : 클라이언트의 요청을 처리한 뒤, 그 결과를 DispatcherServlet에 알려줌.

ModelAndView : 컨트롤러가 처리한 결과 정보 및 뷰 선택에 필요한 정보를 담는다.

ViewResolver : 컨트롤러의 처리 결과를 생성할 뷰를 결정

View : 컨트롤러의 처리 결과 화면을 생성


캐릭터 인코딩 처리를 위한 필터 설정

요청 파라미터의 캐릭터 인코딩이 ISO-8859-1이 아닌경우, request.setCharacterEncoding() 메소드를 사용해서 요청 파라미터의 캐릭터 인코딩을 설정해 줘야 하는데 모든 Controller에서 이 코드를 실행할 수 있지만 그것보다는 서블릿 필터를 이용해서 원하는 요청에 코드를 적용하는것이 더 편리.


web.xml에 추가
 <filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>
   org.springframework.web.filter.CharacterEncodingFilter
  </filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
 </filter>

 <filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>



웹 요청과 컨트롤러 매핑 : HandlerMapping의 구현 클래스

- SimpleUrlHandlerMapping
- BeanNameUrlHandlerMapping
- ControllerClassNameHandlerMapping
- DefaultAnnotationHandlerMapping

컨트롤러 종류

- Controller
- AbstractController
- AbstractCommandController
- SimpleFormController
- AbstractWizardFormController
- ParameterizableViewController
- UrlFilenameViewController
- MultiActionController


Annotatiln을 이용한 Controller의 구현

더 자세히


예외처리

interface Controller의 handleRequest() 메소드는 Exception을 발생할 수 있도록 정의

Controller는 서블릿과 관련된 ServletException뿐만 아니라 NullPointerException과 같은 RuntimeException등 다양한 예외를 발생시킬 수 있다.

보통은 서블릿 엔진이 제공하는 에러 화면이 웹 브라우저에 출력되는데 만약 예외에 따라 알맞은 에러 화면을 출력하고 싶다면 HandlerExceptionResolver를 사용하면 된다.
DispatcherServlet은 HandlerExceptionResolver가 등록되어 있을 경우, 예외 처리를 HandlerExceptionResolver에 맡긴다.

SimpleMappingExceptionResolver 클래스는 HandlerExceptionResolver 인터페이스를 구현하고 있으며, 스프링에서는 현재 SimpleMappingExceptionResolver 클래스만을 제공하고 있다.






  1. seattle
    2008/03/13 13:07 [Edit/Del] [Reply]
    Spring에 푹 빠져있네요 +_+ 계절도 계절이구요 ^^
  2. 2008/03/14 09:27 [Edit/Del] [Reply]
    요새는 새로운 글이 많이 올라오네요.
    스프링이랑 정말 사귀나 봐요.ㅋㅋ

댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret

빈의 후처리

스 프링은 빈의 생명주기에 끼어들어 빈의 설정을 재검토하거나 바꿀 수 있는 2개의 기회를 제공한다. 후처리는 어떤 이벤트가 발생한 후에 처리되는 것이라고 추측할 수 있다. 이벤트란 빈이 설정되거나 인스턴스화되는 것을 말한다. BeanPostProcessor 인터페이스는 빈이 생성되거나 묶인 후에 변경할 수 있는 두개의 기회를 제공


Interface BeanPostProcessor에서는 두개의 메소드를 제공한다

postProcessBeforeInitialization : 빈이 초기화(afterPropertiesSet(), 빈의 커스텀 init-method 호출)되기 직전에 호출

postProcessAfterInitialization : 빈이 초기화된 직후에 호출





빈 팩토리의 후처리

BeanFactoryPostProcesor는 빈 팩토리가 빈의 정의를 로딩한 후와 빈이 인스턴스화되기 전에 빈 팩토리에 대해 후처리를 수행한다.


Interface BeanFactoryPostProcessor에서는 한 개의 메소드를 제공한다.

postProcessBeanFactory : 모든 빈의 정의가 로딩된 다음, BeanPostProcessor빈을 포함한 어떤 빈이라도 인스턴스화되기 이전에 스프링 컨테이너에 의해 호출된다.



BeanFactoryPostProcessor의 유용한 구현 클래스 두 개

PropertyPlaceholderConfigurer

CustomEditorConfigurer



  1. seattle
    2008/02/12 15:50 [Edit/Del] [Reply]
    내용이 너무 어려워요.. 쉽게쉽게 풀어주세요..
  2. 2008/02/12 17:19 [Edit/Del] [Reply]
    스프링이랑 사귀나 봐요.^^
  3. 2008/02/12 17:30 [Edit/Del] [Reply]
    앞으로는 예습한것을 올려 주세요~ ㅋ
  4. 2008/02/25 18:25 [Edit/Del] [Reply]
    상당히 정리를 잘 하시네요
    저랑 완전 비교되는ㅠㅠ
    앞으로 종종와서 Cheating 할께요 ㅎㅎ

댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret

[Spring] 자동 묶기(Autowire)

Posted at 2008/02/12 13:44// Posted in 나만의 작업/Spring

자동 묶기(Autowire)


<bean id=”foo” class= ”com.spring.Foo” autowire= ”autowire type” />


자동 묶기의 네 종류

byName : 묶고자 하는 특성의 이름과 동일한 이름이나 ID를 가진 빈을 컨테이너에서 찾는다. 빈을 찾지 못하면 그 특성을 묶이지 않은 채로 남는다.


byType : 묶 고자 하는 특성의 타입과 동일한 타입을 가진 빈을 컨테이너에서 찾는다. 빈을 찾지 못하면 그 특성은 묶이지 않은 채로 남고, 하나 이상의 빈을 찾게 되면 org.springframework.beans.factory.UnsatisfiedDependencyException을 던진다.


Constructor : 묶고자 하는 빈의 생성자 중 하나의 파라미터와 맞는 하나 이상의 빈을 컨테이너에서 찾는다. 모호한 빈이나 생성자가 발견될 경우 org.springframework.beans.factory.UnsatisfiedDependencyException을 던진다.


Autodetect : constructor에 의한 자동 묶기를 먼저 시도한 다음, byType을 이용한다. 모호함이 발견될 경우 constructor와 byType 경우와 동일한 방법으로 처리한다.




자동 묶기의 모호성 다루기

byType 이나 constructor를 사용하여 자동 묶기를 하는 경우에는 컨테이너가 특성의 타입이나 생성자 인자의 타입에 부합하는 둘 이상의 빈을 찾는 것이 가능하다.


이렇듯 자동 묶기에 사용될 수 있는 모호한 빈들이 존재 할 경우 스프링은 모호성을 분별할 능력이 없으며, 묶고자 하는 빈을 추측하는 대신 예외를 던지는 방법을 선택한다.


자동 묶기를 할 때 그 같은 모호성을 만나게 된다면, 자동 묶기를 하지 않는 것이 가장 단순하면서도 좋은 해결책이다.



  1. 2008/02/12 17:18 [Edit/Del] [Reply]
    스킨이 변했네요..
    봄이 온 것 같네요..

댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret

세터 주입(Setter Injection)의 대안 - 생성자 주입(Constructor Injection)


세터 주입은 빈 특성을 설정하고 묶을 수 있는 직관적인 방법이지만, 한 가지 단점은

변경될 수 있는 모든 특성이 세터 메소드를 통해서 사용할 수 있다고 가정하는 것에 있다. 하지만 빈이 이와 같은 방식으로 작동하기를 원하지 않을 때,

이런 유형의 빈이 인스턴스화될 때에는 어떤 특성도 설정될 수 없으며, 따라서 빈이 유효하지 않은 상태로 있을 가능성이 있다.


어떤 특성들은 빈이 생성될 때 한 번만 설정되고 그 이후에는 변경될 수 없도록 만들고 싶은 경우도 있다.

이는 세터를 통해 모든 특성을 공개하는 경우에는 곤란해진다.




대안은 일부 특성들은 생성자 를 통해 설정될 수 있도록 빈을 설계하는 것이다.

DAO의 DataSource와 같이 반드시 설정돼야 하고 변경되어서는 안 되는 특성이 있는 경우에 특히 유용



생성자 주입은, 어떤 특성을 설정하지 않고서는 인스턴스를 만들 수 없을 때,


세터 주입은, 빈의 특정 메소드에서만 쓴다던가, 필요할 때 설정될 수 있도록 설정하는 것이 좋다.





  1. 2008/02/06 20:29 [Edit/Del] [Reply]
    ㄷㄷㄷ 공부쟁이.
  2. 2008/02/07 08:20 [Edit/Del] [Reply]
    맞아요 공부 엄청 열심히 하시는것 같다는...ㅋㅋ
    최근 글 목록...ㄷㄷㄷ
  3. 2008/02/29 13:14 [Edit/Del] [Reply]
    ㅋㅋ 그래도 셋터가 편해... 아무 이유없이...ㅋㅋ
    이상하게 생성자 Injection은 안땡긴다는...

댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret

[Spring] 빈 묶기(Bean wiring)

Posted at 2008/02/05 14:22// Posted in 나만의 작업/Spring

빈 묶기(Bean wiring)


XML로 묶기 : 다음을 이용해 스프링 컨테이너가 XML을 통한 빈 묶기를 지원한다.

XmlBeanFactory

ClassPathXmlApplicaionContext

FileSystemXmlApplicationContext

XmlWebApplicationContext


프로토타입과 싱글톤 비교

스프링의 모든 빈은 싱글톤. getBean()의 호출에 의해서든 묶기를 통해서든 간에, 컨테이너가 빈을 배포할 때에는 항상 그 빈의 완전히 동일한 인스턴스를 내줄 것이다.

scope="singleton"
scope="prototype"



프로토타입 빈을 정의하는 것이 유리할 때

프로토타입을 정의한다는 것은 실제 하나의 빈을 정의하는 것이 아닌, 청사진을 정의한다는 의미다. 그 다음엔 그 청사진을 바탕으로 빈들이 생성될 것이다.

프로토타입 빈은, 빈을 요청할 때마다 컨테이너가 빈의 유일한 인스턴스를 제공하기 원하면서도 그 빈의 하나 이상의 특성을 스프링을 통해 설정하고자 할 경우에 유용


프로토타입으로 정의

<bean id=”foo” class= ”com.spring.Foo” singleton=false” />

<bean id="foo" class="com.spring.Foo" scope="prototype" />

빈 의 이름을 사용해 getBean()을 호출할 때마다 프로토타입의 새로운 인스턴스가 생성된다. 이로 인해 데이터베이스나 네트워크 연결과 같은 제한된 자원을 사용하는 빈의 경우에는 적합하지 않다. 최소한 새로운 인스턴스가 생성될 때마다 약간의 성능 저하를 겪을 수 있기 때문에, 절대적으로 필요한 경우에만 프로토타입으로 빈을 정의하자.


참고)
dW문서  
'Spring 2.0: 요란스럽지 않은 진화의 흐름' 내용 중

Spring의 기반을 이루는 IoC 컨테이너에서는 앞서 언급한 XML 설정 이외에 빈(bean)의 스코프(scope)가 추가된 것이 주요 개선 사항이다.

Singleton과 prototype으로만 존재하던 스코프에 request, sessionglobal session 스코프가 추가되었고, 사용자가 정의한 스코프를 사용할 수도 있다. 이러한 개선은 개발자가 직접 HTTP Request나 Session을 다루는 일을 줄여주고, 웹 어플리케이션의 커뮤니케이션 불연속성 문제를 다소나마 해결해줄 것으로 보인다.


Scope Description

singleton

Scopes a single bean definition to a single object instance per Spring IoC container.

prototype

Scopes a single bean definition to any number of object instances.

request

Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session

Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session

Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.


출처 : spring 2.0 reference 중

 

초기화와 소멸

빈의 정이 내에 커스텀 init-method를 선언함으로써 빈이 인스턴스화되는 즉시 호출될 메소드를 지정할 수 있다.

커스텀 destroy -method는 빈이 컨테이너로부터 제거되기 직전에 호출될 메소드를 지정한다.


<bean id=”foo” class= ”com.spring.Foo” init-method= ”setup ” destroy -method= ”teardown” />


Example) 커넥션 풀링(connection pooling) 빈


public class MyConnectionPool{

public void initialize(){

//커넥션 풀 초기화

}

}

public void close(){

//연결 해제

}

}


빈의 정의는,

<bean id=”connectionPool” class= ”com.spring.MyConnectionPool” init-method= ”initialize” destroy-method= ”close” />


MyConnectionPool이 인스턴스화되자마자 initialize() 메소드가 호출,

빈이 컨테이너로부터 제거되기 직전에 close() 메소드를 호출


스프링은 또 다른 방법으로, InitializingBean과 DisposableBean이라는 동일한 역할을 하는 두개의 인터페이스를 제공한다.


InitializingBean 인터페이스는 afterPropertiesSet() 메소드 : 빈의 모든 특성이 설정된 후에 한 번 호출.

DisposableBean 인터페이스는 destroy () : 빈이 컨테이너로부터 제거될 때 호출



이 방법은 인터페이스를 구현하는 빈을 스프링 컨테이너가 자동으로 탐지하며, 별다른 설정없이도 메소드를 호출해준다(XML 손대지 않고) 하지만, 인터페이스를 구현하게 되면, 빈은 스프링의 API에 묶이게 되어 버린다.

빈을 초기화하고 소멸시킬 때 가능하다면 init-method와 destroy-method 정의에 의존하는게 좋은 방법이다. 스프링의 인터페이스를 사용할만한 유일한 경우는 스프링 컨테이너 안에서 특별하게 사용될 프레임워크 빈을 개발할 때뿐이다.




  1. iolo
    2008/02/05 19:29 [Edit/Del] [Reply]
    singleton="false"라고 쓰는 방식은 deprecated임다.
    scope="prototype"이라고 쓰는 방식으로 바뀌었습니당~

댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret

스프링 컨테이너의 두 종류


컨테이너 안의 빈(Bean)

컨 테이너는 스프링 프레임워크의 핵심이다. 스프링 컨테이너는 제어 역행(IoC)을 사용해 애플리케이션을 구성하는 컴포넌트들을 관리한다. 여기에는 협력하는 컴포넌트간의 연관관계를 생성하는 것이 포함된다. 그렇게 함으로써 객체는 좀더 명확하게 이해할 수 있고, 재사용이 가능해지며, 단위테스트가 쉬워진다.


스프링 컨테이너의 두 종류


org .springframework.beans.factory.BeanFactory 인터페이스로 정의되는 빈 팩토리

기본적인 의존성 주입을 지원하는 가장 간단한 형태의 컨테이너



org .springframework.context.ApplicationContext 인터페이스로 정의되는 어플리케이션 컨텍스트.

프로퍼티 파일의 텍스트 메시지를 해석하는 능력이나 애플리케이션 이벤트를 관련된 이벤트 리스너에 발행하는 능력 등과 같은 애플리케이션 프레임워크 서비스를 제공함으로써 빈팩토리의 개념 위에 구현된 것.



빈 팩토리(BeanFactory)

팩토리 디자인 패턴을 구현한 것. 빈 팩토리는 빈을 생성하고 분배하는 책임을 지는 클래스

커스텀 초기화 메소드(initialization method)와 소멸 메소드(destruction method)를 호출함으로써 빈의 생명주기에 개입할 수 있다.


org .springframework.beans.factory.xml.XmlBeanFactory 가 가장 유용한데, XML 파일에 기술돼있는 정의를 바탕으로 빈을 로딩한다.


BeanFactory factory = new XmlBeanFactory(new FileInputStream( “beans.xml ”));

MyBean myBean = (MyBean) factory.getBean( “myBean ”);


빈 팩토리에게 XML 파일로부터 빈에 대한 정의를 읽어오라고 알려준다 . 빈 팩토리가 빈 을인스턴스화하는 것은 아니고 빈은 빈 팩토리에 “늦게 ”로딩되는데, 이 말은 빈 팩토리가 빈의 정의는 즉시 로딩하는 반면, 빈 자체가 필요하게 되기 전까지는 인스턴스화 하지 않는다.

getBean()이 호출되면, 팩토리는 의존성 주입을 이용해 빈을 인스턴스화하고 빈의 특성을 설정 시작. 여기서 빈의 일생이 시작된다.


애플리케이션 컨텍스트

BeanFactory와 유사한 기능을 제공하지만 좀 더 많은 기능을 제공하는 ApplicationCont ext


국제화(I18N) 지원을 포함해 텍스트 메시지를 해석하는 수단을 제공

이미지 등과 같은 자원을 로딩하는 범용적인 방법을 제공

리스너로 등록돼있는 빈에 이벤트를 발행할 수 있다.


구현 클래스 중 일반적으로 사용되는 세 개 의 클래스

ClassPathXmlApplicationContext : 클래스 경로에 있는 XML 파일로부터 컨텍스트 정의를 로딩하며, 컨텍스트 정의를 클래스 경로에 있는 자원으로 취급한다.

FileSystemXmlApplicationContext : 파일 시스템에 있는 XML 파일로부터 컨텍스트 정의를 로딩.

XmlWebApplicationContext : 웹 애플리케이션에 포함돼 있는 XML 파일로부터 컨텍스트 정의를 로 딩




애플리케이션 컨텍스트와 빈 팩토리의 또 다른 차이점 은 싱글톤(singleton) 빈을 로딩하는 방법에 있다. 빈 팩토리는 getBean() 메소드가 호출될 때까지 빈의 생성을 미룬다. 즉 빈 팩토리는 모든 빈을 lazy loading한다.




애플리케이션 컨텍스트는 싱글톤 빈을 미리 로딩 (preloading) 함으로써, 그 빈이 필요할 때 즉시 사용될 수 있도록 보장해준다. 즉 애플리케이션은 빈이 생성되기를 기다릴 필요가 없다는 뜻


댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret

[Spring] Spring 환경설정

Posted at 2008/01/28 02:13// Posted in 나만의 작업/Spring

/**************************************************************************

스프링 공부하면서 정리한 내용을 그냥 올려봅니다.
혼자 놀다가 중간에 에러난 부분도 기억삼아 올려놓은것이어서
내용이 틀릴수도 있답니다.
이글은 "스프링 인 액션" 책을 열심히 보며 쓴 글입니다~

@author 버리

**************************************************************************/


프로젝트 설정


1.    Spring 다운로드(http://www.springframework.org/download)

최신버젼을 다운로드하고, 사용할 JAR파일들을 dist 디렉토리에서 선택한 다음에

빌드 클래스 경로와 애플리케이션 클래스 경로에 추가한다.


2.    프로젝트 위치 설정(src, lib등 원하는 폴더를 생성)


3.    Ant 빌드 파일 작성

에러

-      [javac] BUILD FAILED: [build file location here]
Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK

-       출처 : http://www.dynamicobjects.com/d2r/archives/002591.html

-      메뉴바에서 Windows/Preferences 다이얼로그를 열어서 Ant/Runtime

-      jsdk tools.jar ant 클래스 패스에 추가해 주시면 됩니다.

 

완성된 ant 빌드 파일

 

<?xml version="1.0"?>

<project name="spring_example" default="compile" basedir=".">

<property name="spring.home" location="D:\dev\spring-framework-2.5.1" />

<property name="spring.lib.dir" location="${spring.home}/dist"/>

<property name="spring.depends.dir" location="${spring.home}/lib"/>

 

<property name="build.dir" location="build"/>

<property name="build.prod.dir" location="${build.dir}/prod"/>

<property name="src.dir" location="src"/>

<property name="java.src.dir" location="${src.dir}/java"/>

<property name="webapp.dir" location="${src.dir}/webapp" />         

<property name="lib.dir" location="lib"/>

 

<path id="project.classpath">

           <pathelement location="${build.prod.dir}" />

           <fileset dir="${lib.dir}">

                      <include name ="*.jar" />

           </fileset>

           <fileset dir="${spring.lib.dir}" includes="*.jar"/>

           <fileset dir="${spring.depends.dir}" includes="**/*.jar"/>

</path>

<target name="prepare">

           <mkdir dir="${build.prod.dir} "/>

</target>

<target name="compile" depends="prepare">

           <javac srcdir="${src.dir}" destdir="${build.prod.dir}">

                      <classpath refid="project.classpath" />

           </javac>

</target>

</project>

 

 

4.    Web.xml 작성 후 application run

-      코드에는 에러가 없고 실행하면 에러나는

Exception in thread “main” java.lang.NoClassDefFoundError:

org/apache/commons/logging/LogFactory

-      해당 프로젝트의 build pathJakarta-commons commons-logging.jar 파일을 추가 (당연히  commons-logging을 쓰려면^^ 깜빡할까봐~)


5.    Log4j.properties 파일 작성

 

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=[%5p] %d{HH:mm:ss} %c{1} - %m%n

 

log4j.rootLogger=WARN,stdout

 

log4j.appender.logfile=org.apache.log4j.FileAppender

log4j.appender.logfile.File=target/spring.log

log4j.appender.logfile.layout=org.apache.log4j.PatternLayout

log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

 

log4j.category.com.springinaction=DEBUG

log4j.category.org.springframework=WARN

log4j.category.net.sf.hibernate=WARN

log4j.category.net.sf.acegisecurity=DEBUG

 

l  SpringIDE설치 :

홈페이지: http://springide.org


설치 및 업데이트 주소: http://springide.org/updatesite/


Spring IDE 간단하게 설명한 안영회님의 블로그 내용 http://younghoe.info/148


Tag 스프링
  1. 2008/01/28 09:12 [Edit/Del] [Reply]
    매일 공부만 하나봐요..^^
    앞으로 연애하셔야죠^^
    이미 하고 있으려나...

    감기 조심해요.
  2. 2008/01/28 10:15 [Edit/Del] [Reply]
    나도 오늘은 스프링을 깔아(?)봐야지.ㅎ.

댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret

[Spring] Hitting the database

Posted at 2007/11/04 20:56// Posted in 나만의 작업/Spring

* Hitting the database


1) Spring의 DataAccessException

java.sql.SQLException은 checked Exception입니다. 즉, 개발자가 try-catch로 잡아줘야 합니다.

이는 코드를 난잡하게 만들수 있습니다.  그리고 SQLException이 제공하는 예외는 Spring에 비해서 매우 종류가 많지 않습니다.

 
DataAccessException은 SQLException이나 HibernateException등과 같이 특정 기술에 의존적인 예외를 던지지 않기때문에, 데이터 접근 인터페이스가 구현에 의존적인 예외가 아닌 스프링의 일반적인 DataAccessException을 던지게 함으로써, 특정한 퍼시스턴스 구현에 결합되는 일을 방지합니다.

 
DataAccessException은 RuntimeException이기 때문에 unchecked Exception에 속하기 때문에 개발자가 반드시 처리하지 않아도 됩니다. unchecked Exception이 발생하는 경우는 대개 복구가 불가능한 것이기 때문에 개발자가 직접 처리해야 할 필요는 없습니다. 만약 복구가 가능한 것이라면 예외를 잡아 호출 스택으로 전달되도록 할 수도 있습니다. (처리하고 싶으면 잡아서 처리하고, 하고 싶지 않으면 Spring에서 잡도록 내버려 둬도 됩니다.)

 
Spring의 DAO Exception 분류 체계는 매우 세밀하기 때문에, 서비스 객체가 잡고자 하는 exception의 타입과 호출 스택에 전달하고자 하는 exception을 정확히 선택할 수 있습니다.


2) Spring에서 데이터 접근

Spring은 데이터 접근 프로세스에 있어서 고정된(변하지 않는) 부분을 template(템플릿)으로 가변적인(변하는) 부분을 callback(콜백)으로 구분합니다.

template은 프로세스의 고정된 부분을 관리하는 반면, callback은 구체적인 구현을 넣어야 하는 장소입니다.

 
template은 데이터 저장소로의 연결 취득, 트랜잭션 제어, 자원반환, 예외 처리등하고싶을 일을 구현하기 위해 중복적으로 해야하는 작업들입니다.


callback 인터페이스의 구현 클래스는 질의문 생성, 파라미터 바인딩, 결과 집합 마샬링(marshalling) 등 애플리케이션에 특정적인 부분을 정의합니다.


  

[그림] 스프링 DAO 템플릿과 콜백 클래스의 역할 ( 차후에 추가 )


* JDBC 코드의 문제점은 무엇일까요? (Quiz)


Spring에서의 JdbcTemplate

Spring이 JDBC 프레임워크는 자원 관리와 에러 처리의 부담을 떠맡음으로써 JDBC 코드를 깨끗하게 만들어 줍니다.

 
JdbcTemplate 클래스가 작업하기 위해 필요한 것은 DataSource뿐입니다.


- JdbcTemplate과 함께 쓰이는 Class

//---------------------------------------------------------------
// 데이터 쓰기
//---------------------------------------------------------------

  • PreparedStatementCreator : 이 인터페이스의 구현 클래스는 PreparedStatement를 생성시킬 책임을 갖는다.  이 인터페이스를 구현할 때에는 인자로 넘어온 Connection으로부터 PreparedStatement를 생성하고 리턴해줘야 한다. 그러나 예외 처리에 대해서는 신경쓰지 않아도 된다.

    /**
     * One of the two central callback interfaces used by the JdbcTemplate class.
     * This interface creates a PreparedStatement given a connection, provided
     * by the JdbcTemplate class. Implementations are responsible for providing
     * SQL and any necessary parameters.
     */
    public interface PreparedStatementCreator {


        /**
         * Create a statement in this connection. Allows implementations to use
         * PreparedStatements. The JdbcTemplate will close the created statement.
         * @param con Connection to use to create statement
         * @return a prepared statement
         * @throws SQLException there is no need to catch SQLExceptions
         * that may be thrown in the implementation of this method.
         * The JdbcTemplate class will handle them.
         */
        PreparedStatement createPreparedStatement(Connection con) throws SQLException;

    }

  • SqlProvider : SqlProvider 인터페이스의 getSql() 이라는 하나의 메소드를 구현함으로써 클래스가 SQL 문자열을 JdbcTemplate 클래스에 제공할 수 있게 된다. 이렇게 하면  JdbcTemplate 클래스가 자신이 실행하는 모든 SQL 문장에 대해 로그를 남기는 것이 가능해진다.

    public interface SqlProvider {

        /**
         * Return the SQL string for this object, i.e.
         * typically the SQL used for creating statements.
         * @return the SQL string, or <code>null</code>
         */
        String getSql();

    }


  • PreparedStatementSetter : PreparedStatementCreatr를 보완. 파라미터를 세팅하기만 하고 모든 예외 처리는 JdbcTemplate 클래스가 해 줄 것이다.

    public interface PreparedStatementSetter {

        /**
         * Set parameter values on the given PreparedStatement.
         * @param ps the PreparedStatement to invoke setter methods on
         * @throws SQLException if a SQLException is encountered
         * (i.e. there is no need to catch SQLException)
         */
        void setValues(PreparedStatement ps) throws SQLException;

    }


  • BatchPreparedStatement : 갱신하고자 하는 레코드가 둘 이상일 경우.

    public interface BatchPreparedStatementSetter {

        /**
         * Set parameter values on the given PreparedStatement.
         * @param ps the PreparedStatement to invoke setter methods on
         * @param i index of the statement we're issuing in the batch, starting from 0
         * @throws SQLException if a SQLException is encountered
         * (i.e. there is no need to catch SQLException)
         */
        void setValues(PreparedStatement ps, int i) throws SQLException;

        /**
         * Return the size of the batch.
         * @return the number of statements in the batch
         */
        int getBatchSize();

    }


    // ------------------------------------------------------------------------------------
    //  데이터 읽기
    // ------------------------------------------------------------------------------------


    스프링을 사용하지 않은 이전의 JDBC 에서는 데이터베이스에 질의를 한 후에 ResultSet을 순환하여
    결과를 얻어내야 하는데 스프링은 그 일을 대신 해 준다.

  • RowCallbackHandler

  • RowMapperResultReader -> 2.x 버젼부터 RowMapperResultSetExtractor 사용

  • CallableStatementCallback : 저장 프로시저 호출하기


3) DaoSupport

DaoSupport class사용시의 문제점

MemberDaoImpl, PostDaoImpl, BoardDaoImpl 등의 class가 있다고 하면 JdbcTemplate을 이용하여 구현을 하려고 하면


JdbcTemplate을 설정하는 코드가 각각의 클래스의 Setter 메소드를 이용하여 세팅이 되야하는데, 이것을 중복을 유발합니다.


DAO 클래스마다 중복적으로 발생하는 JdbcTemplate설정을 추상화 계층으로 끌어올려 JdbcDaoSupport Class를 만들어서, Support 클래스는 데이터베이스와의 통신에 사용되는 클래스에 직접적으로 접근할 수 있도록 해줍니다.


JdbcDaoSupport클래스는 Connection 객체를 얻기 위해 getConnection() 메소드를 호출하면 됩니다.


JdbcDaoSupport 클래스를 이용하면 DataSource를 Spring 설정파일에서 매핑시켜주지 않아도 됩니다.


4) Spring의 ORM 프레임워크 지원 기능

  •  lazy loading : 객체들의 관계 전체를 그대로 얻기 원하지 않을 경우 필요로 하는 데이터만 가져올 수 있도록 해줌
  • eager fetching : ( <-> lazy loading) : 하나의 질의로 전체 객체들을 한번에 얻어오는 것
  • caching : 주로 읽기만 하는 데이터의 경우 매번 Database에서 가져오기를 원치 않을 때 사용.
  • cascading : 제약사항

5) Hibernate와의 연동

Hibernate에서는 SessionFactory를 이용하여 session객체를 생성하는 것이 가장 중요하고,

설정파일에서 SessionFactory를 property로 추가(DataSource)합니다.


6) Caching

Cache 설정파일을 만들고, Spring 설정파일에서 cache 설정파일이 어디있는지 설정해주고,

cache대상과 비울 대상을 메소드로 설정합니다.(XML이나 Annotation으로 설정)








  1. 2007/11/05 09:30 [Edit/Del] [Reply]
    정말 공부 열심히 하나봐요...
    버리님 제자로 들어가야겠어요.^^
  2. seattle
    2007/11/05 11:23 [Edit/Del] [Reply]
    버리 선생님 저도 껴주세요 ㅋㅋ
  3. 2007/11/07 09:37 [Edit/Del] [Reply]
    내가 이런데 댓글 안 다는거 알지?
    K군 표현에 의하면 전락한 개발자라... ㅋㅋ

    타오를때 열심히 해라~ 그래야 MIT도 가고 스탠퍼드도 가고 버클리도 가고 하니까~

댓글을 남겨주세요

Name *

Password *

Link (Your Homepage or Blog)

Comment

Secret