'Spring'에 해당되는 글 11건
- [Spring] @Autowired의 Before/After (2) 2009/04/29
- [iBATIS] 7. iBATIS + Spring + transaction 2008/09/02
- [iBATIS] 6. iBATIS + Spring 2008/09/01
- [dW] Acegi로 자바 애플리케이션 보안화 하기, Part 1: 아키텍처 개요와 보안 필터 (한글) (4) 2008/03/23
- [Spring] 스프링에서 VelocityTools 환경설정 (2) 2008/03/20
- [Spring] Bean과 BeanFactory의 후처리 (8) 2008/02/12
- [Spring] 자동 묶기(Autowire) (2) 2008/02/12
- [Spring] 세터 주입(Setter Injection)의 대안 (5) 2008/02/05
- [Spring] 빈 묶기(Bean wiring) (2) 2008/02/05
- [Spring] Hitting the database (8) 2007/11/04
- 5회 스프링 프레임웍 사용자 모임에 다녀왔습니다. (10) 2007/10/28
[Spring] @Autowired의 Before/After
Posted at 2009/04/29 15:35// Posted in 나만의 작업/SpringapplicationContext.xml에서 설정
<bean id="empDao" class="EmpDao" /> <bean id="empManager" class="EmpManager"> <property name="empDao" ref="empDao" /> </bean>
public class EmpManager { private EmpDao empDao; public EmpDao getEmpDao() { return empDao; } public void setEmpDao(EmpDao empDao) { this.empDao = empDao; } ... }
After
<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; }
'나만의 작업 > Spring' 카테고리의 다른 글
| [Spring] @Autowired의 Before/After (2) | 2009/04/29 |
|---|---|
| [Spring] 스프링에서 VelocityTools 환경설정 (2) | 2008/03/20 |
| [Spring] 스프링 MVC를 이용한 웹 요청 처리 (4) | 2008/03/13 |
| [Spring] Bean과 BeanFactory의 후처리 (8) | 2008/02/12 |
| [Spring] 자동 묶기(Autowire) (2) | 2008/02/12 |
| [Spring] 세터 주입(Setter Injection)의 대안 (5) | 2008/02/05 |
| [Spring] 빈 묶기(Bean wiring) (2) | 2008/02/05 |
| [Spring] 스프링 컨테이너의 두 종류 (0) | 2008/02/05 |
| [Spring] Spring 환경설정 (4) | 2008/01/28 |
-
[NC]...YellOw2009/04/29 22:13 [Edit/Del] [Reply]인자 저도 스프링 공부해야하는데 요기서 많은 도움을 얻을 수 있을거 같네요!!
-
버리야2009/05/06 10:33 [Edit/Del]헷갈리는 일이 자주 생기시겠네용...ㅋㅋ
-
[iBATIS] 7. iBATIS + Spring + transaction
Posted at 2008/09/02 10:03// Posted in 나만의 작업/iBatis7. iBATIS + Spring + transaction
1. 코드 기반의 트랜잭션 처리 (Progrmmatic Transaction)
2. 선언적 트랜잭션 (Declarative Transaction)
- <tx:advice> 태그를 이용
- TransactionProxyFactoryBean 태그를 이용
- @Transactional 어노테이션을 이용
<tx:advice> 태그 이용
<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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean id="fooService" class="x.y.service.DefaultFooService"/>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
<aop:pointcut id="fooServiceOperation" expression="execution(* x.y.service.FooService.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
@ Transactional 어노테이션을 이용
@Transactional(readOnly = true)
public class DefaultFooService implements FooService {
public Foo getFoo(String fooName) {
// do something
}
// these settings have precedence for this method
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void updateFoo(Foo foo) {
// do something
}
}
<bean id="fooService" class="x.y.service.DefaultFooService"/>
<tx:annotation-driven transaction-manager="txManager"/>
'나만의 작업 > iBatis' 카테고리의 다른 글
| [iBatis] iBatis에서 Log4j를 이용하여 쿼리를 로그로 남기려면? (4) | 2009/01/20 |
|---|---|
| [iBatis] 자동 생성 Key (2) | 2009/01/18 |
| [iBatis] 자바빈즈와 Map 타입의 결과 (0) | 2009/01/18 |
| [iBATIS] 8. Annotation 기반으로 JUnit4를 이용한 Spring TDD ~ 9. Reference (4) | 2008/09/03 |
| [iBATIS] 7. iBATIS + Spring + transaction (0) | 2008/09/02 |
| [iBATIS] 6. iBATIS + Spring (0) | 2008/09/01 |
| [iBATIS] 5. Transaction (2) | 2008/09/01 |
| [iBATIS] 4. How to (2) | 2008/08/29 |
| [iBATIS] 1.Overview ~ 3. Introduce iBATIS (4) | 2008/08/28 |
[iBATIS] 6. iBATIS + Spring
Posted at 2008/09/01 19:57// Posted in 나만의 작업/iBatis6. iBATIS + Spring
SqlMapClientFactoryBean
(org.springframework.orm.ibatis.SqlMapClientFactoryBean)
SqlMapClientTemplate
(org.springframework.orm.ibatis.SqlMapClientTemplate)
SqlMapClientDaoSupport
(org.springframework.orm.ibatis.support.SqlMapClientDaoSupport)
스프링의 iBATIS 연동지원
iBATIS 에서 데이터베이스 연동을 처리할 때 사용되는 SqlMapClient 역시 JDBC 프로그램을 할 때와 마찬가지로 try-catch 블록을 사용해서 예외를 처리해 주어야 한다 .
또한 에러원인에 따라 알맞은 예외를 발생시키기보다는 SQLException 을 발생하고 있다 .
스프링은 SqlMapClient 를 사용할 때 발생하는 코드 중복을 없애고 SQLException 을 스프링이 제공하는 예외 클래스로 변환해 주는 SqlMapClientTempalte 클래스를 제공하고 있다 .
1.
SqlMapClient 를 위한 스프링 설정
스프링이 제공하는 SqlMapClientTemplate 클래스는 내부적으로 iBATIS 의 SqlMapClient 를 사용한다 .
스프링은 SqlMapClient 를 스프링 설정 파일에서 쉽게 설정할 수 있도록 돕는 SqlMapClientFactoryBean
클래스를 제공하고 있다 .
이 클래스를 사용하면 SqlMapClient 를 스프링 빈으로 설정할 수 있다 .
dataSource 프로퍼티에는 DataSource 를 전달하며 , configLocation 프로퍼티는 iBATIS 설정 파일을 명시
2.
SqlMapClientTemplate 을 이용한 DAO 구현
SqlMapClient 를 위한 빈을 설정했다면 SqlMapClientTemplate 을 이용해서 iBATIS 를 연동할 수 있다 .
SqlMapClientTemplate
클래스는 iBATIS 의 SqlMapClient
클래스가 제공하는 대부분의 메소드와 동일한 이름과 파라미터 타입 , 리턴 타입을 갖는 메소드를 정의하고 있다.
차이점이 있다면 SQLException 을 발생하는 대신 스프링이 제공하는 예외를 발생한다 .
iBATIS 의 SqlMapExecutor 를 직접 사용하고 싶다면 ,
SqlMapClientCallback 인터페이스의 구현 객체를 전달받는 execute() 메소드를 사용하면 된다 .
SqlMapClientCallback
구현 객체의 doInSqlMapClient()
메소드에 SqlMapExecutor 파라미터가 전달되므로 , 직접 SqlMapExecutor 를 사용해서 데이터베이스 연동을 구현할 수 있다 .
3.
SqlMapClientDaoSupport 클래스를 이용한 DAO 구현
스프링은 SqlMapClientTemplate 클래스를 DAO 클래스에서 좀 더 쉽게 사용할 수 있도록 하기 위해 SqlMapClientDaoSupport 클래스를 제공한다 .
이 클래스를 상속받은 클래스는 sqlMapClientTemplate 프로퍼티를 통해서 SqlMapClientTemplate 를 전달받는다 .
'나만의 작업 > iBatis' 카테고리의 다른 글
| [iBatis] iBatis에서 Log4j를 이용하여 쿼리를 로그로 남기려면? (4) | 2009/01/20 |
|---|---|
| [iBatis] 자동 생성 Key (2) | 2009/01/18 |
| [iBatis] 자바빈즈와 Map 타입의 결과 (0) | 2009/01/18 |
| [iBATIS] 8. Annotation 기반으로 JUnit4를 이용한 Spring TDD ~ 9. Reference (4) | 2008/09/03 |
| [iBATIS] 7. iBATIS + Spring + transaction (0) | 2008/09/02 |
| [iBATIS] 6. iBATIS + Spring (0) | 2008/09/01 |
| [iBATIS] 5. Transaction (2) | 2008/09/01 |
| [iBATIS] 4. How to (2) | 2008/08/29 |
| [iBATIS] 1.Overview ~ 3. Introduce iBATIS (4) | 2008/08/28 |
[dW] Acegi로 자바 애플리케이션 보안화 하기, Part 1: 아키텍처 개요와 보안 필터 (한글)
Posted at 2008/03/23 23:32// Posted in 나만의 작업/dW공부해 봐서 마침 dW에 글이 있나 찾아보니 역시나 있군요~
우리나라 말로하면 "아저씨"(지극히 저의 개인적인 생각)란 이름과 비슷한 아씨지(어떤분은 머 다른말로 표현하셨던데 어쩜 그게 더 비슷한거 같기도 하고)
아무튼!
What is Acegi Security?
Acegi Security is a powerful, flexible security solution for enterprise software, with a particular emphasis on applications that use Spring. Using Acegi Security provides your applications with comprehensive authentication, authorization, instance-based access control, channel security and human user detection capabilities.
머~ 이런 일을 한다고 합니다~로그인할때 해당 유저가 로그인할 권한이 있는지 Acegi 보안을 통해 접근할지 못하게 할지등등의 일을
처리할 수 있습니다.
Acegi로 자바 애플리케이션 보안화 하기, Part 1: 아키텍처 개요와 보안 필터 (한글)
이 문서에서의 내용은 Spring 프레임워크를 사용하여 IoC와 XML설정 파일을 이용해 보안처리를 하기위해 Acegi를 적용한 간단한 샘플 예제가 있습니다.
설정으로 보안과 관련해서 처리해야 할 일들을 줄일 수 있다면야~ 좋겠죠~?
'나만의 작업 > dW' 카테고리의 다른 글
| [dW] Practically Groovy: Reduce code noise with Groovy (0) | 2008/06/24 |
|---|---|
| [dW] Ajax에서 XML 처리하기 (2) | 2008/05/28 |
| [dW] Learn 10 good XML usage habits (2) | 2008/05/23 |
| [dW] XStream으로 자바 객체를 XML로 직렬화하기 (6) | 2008/05/22 |
| [dW] HTML 5와 XHTML 2에 관련된 글(dW문서와 그외) (3) | 2008/04/28 |
| [dW] Ajax 오버홀(overhaul), Part 1: Ajax와 jQuery로 기존 사이트 개선하기 (한글) (4) | 2008/04/20 |
| [dW] Acegi로 자바 애플리케이션 보안화 하기, Part 1: 아키텍처 개요와 보안 필터 (한글) (4) | 2008/03/23 |
| [dW] 클래스 로딩 문제 분석하기 (4) | 2008/03/04 |
| [dW] IBM developerWorks 리뷰 블로거 2.0 선발과 Mylyn 2.0 통합된 태스크 관리 & 자동화된 콘텍스트 관리 (8) | 2008/02/23 |
-
2008/03/25 12:42 [Edit/Del] [Reply]스프링을 무지 열심히 공부하나 봐요...
스프링에 관심이 도통 가지 않는 것을 보니
벽 보고 반성 좀 해야겠습니다.
갑자기 날씨가 추워졌어요 감기 조심해요. -
[Spring] 스프링에서 VelocityTools 환경설정
Posted at 2008/03/20 09:05// Posted in 나만의 작업/Spring필요한 설정을 기억하기 위해 기록합니다.
VelocityTools는 벨로시티 템플릿에서 숫자나 날짜, url등의 포맷팅을 지원하는 툴이고,
VelocityTools프로젝트에는 GenericTools, VelocityView, VelocityStruts 세개의 부분으로 나눠져 있습니다.
보통 GenericTools를 많이 쓸일이 많기 때문에~ 조금 정리해보면,
- 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 파일을 하나 만들어서
<toolbox>
<tool>
<key>esc</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.EscapeTool</class>
</tool>
</toolbox>
genericTool의 EscapeTool을 사용하는데 velocity에서 esc라는 키워드를 이용해서 쓰겠다~
스프링에서 Properties파일을 따로 정의했다고 하면(따로 빼 놓았다면)
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
스프링의 설정파일에서
<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파일에서
결과는
참고 :
[Velocity] 스프링 프레임워크에서 사용하기
http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/EscapeTool.htmlhttp://forum.springframework.org/archive/index.php/t-10926.html
'나만의 작업 > Spring' 카테고리의 다른 글
| [Spring] @Autowired의 Before/After (2) | 2009/04/29 |
|---|---|
| [Spring] 스프링에서 VelocityTools 환경설정 (2) | 2008/03/20 |
| [Spring] 스프링 MVC를 이용한 웹 요청 처리 (4) | 2008/03/13 |
| [Spring] Bean과 BeanFactory의 후처리 (8) | 2008/02/12 |
| [Spring] 자동 묶기(Autowire) (2) | 2008/02/12 |
| [Spring] 세터 주입(Setter Injection)의 대안 (5) | 2008/02/05 |
| [Spring] 빈 묶기(Bean wiring) (2) | 2008/02/05 |
| [Spring] 스프링 컨테이너의 두 종류 (0) | 2008/02/05 |
| [Spring] Spring 환경설정 (4) | 2008/01/28 |
[Spring] Bean과 BeanFactory의 후처리
Posted at 2008/02/12 13:44// Posted in 나만의 작업/Spring빈의 후처리
스 프링은 빈의 생명주기에 끼어들어 빈의 설정을 재검토하거나 바꿀 수 있는 2개의 기회를 제공한다. 후처리는 어떤 이벤트가 발생한 후에 처리되는 것이라고 추측할 수 있다. 이벤트란 빈이 설정되거나 인스턴스화되는 것을 말한다. BeanPostProcessor 인터페이스는 빈이 생성되거나 묶인 후에 변경할 수 있는 두개의 기회를 제공
Interface BeanPostProcessor에서는 두개의 메소드를 제공한다
postProcessBeforeInitialization : 빈이 초기화(afterPropertiesSet(), 빈의 커스텀 init-method 호출)되기 직전에 호출
postProcessAfterInitialization : 빈이 초기화된 직후에 호출
빈 팩토리의 후처리
BeanFactoryPostProcesor는 빈 팩토리가 빈의 정의를 로딩한 후와 빈이 인스턴스화되기 전에 빈 팩토리에 대해 후처리를 수행한다.
Interface BeanFactoryPostProcessor에서는 한 개의 메소드를 제공한다.
postProcessBeanFactory : 모든 빈의 정의가 로딩된 다음, BeanPostProcessor빈을 포함한 어떤 빈이라도 인스턴스화되기 이전에 스프링 컨테이너에 의해 호출된다.
BeanFactoryPostProcessor의 유용한 구현 클래스 두 개
PropertyPlaceholderConfigurer
CustomEditorConfigurer
'나만의 작업 > Spring' 카테고리의 다른 글
| [Spring] @Autowired의 Before/After (2) | 2009/04/29 |
|---|---|
| [Spring] 스프링에서 VelocityTools 환경설정 (2) | 2008/03/20 |
| [Spring] 스프링 MVC를 이용한 웹 요청 처리 (4) | 2008/03/13 |
| [Spring] Bean과 BeanFactory의 후처리 (8) | 2008/02/12 |
| [Spring] 자동 묶기(Autowire) (2) | 2008/02/12 |
| [Spring] 세터 주입(Setter Injection)의 대안 (5) | 2008/02/05 |
| [Spring] 빈 묶기(Bean wiring) (2) | 2008/02/05 |
| [Spring] 스프링 컨테이너의 두 종류 (0) | 2008/02/05 |
| [Spring] Spring 환경설정 (4) | 2008/01/28 |
[Spring] 자동 묶기(Autowire)
Posted at 2008/02/12 13:44// Posted in 나만의 작업/Spring자동 묶기(Autowire)
자동 묶기의 네 종류
byName : 묶고자 하는 특성의 이름과 동일한 이름이나 ID를 가진 빈을 컨테이너에서 찾는다. 빈을 찾지 못하면 그 특성을 묶이지 않은 채로 남는다.
byType : 묶 고자 하는 특성의 타입과 동일한 타입을 가진 빈을 컨테이너에서 찾는다. 빈을 찾지 못하면 그 특성은 묶이지 않은 채로 남고, 하나 이상의 빈을 찾게 되면 org.springframework.beans.factory.UnsatisfiedDependencyException을 던진다.
Constructor : 묶고자 하는 빈의 생성자 중 하나의 파라미터와 맞는 하나 이상의 빈을 컨테이너에서 찾는다. 모호한 빈이나 생성자가 발견될 경우 org.springframework.beans.factory.UnsatisfiedDependencyException을 던진다.
Autodetect : constructor에 의한 자동 묶기를 먼저 시도한 다음, byType을 이용한다. 모호함이 발견될 경우 constructor와 byType 경우와 동일한 방법으로 처리한다.
자동 묶기의 모호성 다루기
byType 이나 constructor를 사용하여 자동 묶기를 하는 경우에는 컨테이너가 특성의 타입이나 생성자 인자의 타입에 부합하는 둘 이상의 빈을 찾는 것이 가능하다.
이렇듯 자동 묶기에 사용될 수 있는 모호한 빈들이 존재 할 경우 스프링은 모호성을 분별할 능력이 없으며, 묶고자 하는 빈을 추측하는 대신 예외를 던지는 방법을 선택한다.
자동 묶기를 할 때 그 같은 모호성을 만나게 된다면, 자동 묶기를 하지 않는 것이 가장 단순하면서도 좋은 해결책이다.
'나만의 작업 > Spring' 카테고리의 다른 글
| [Spring] @Autowired의 Before/After (2) | 2009/04/29 |
|---|---|
| [Spring] 스프링에서 VelocityTools 환경설정 (2) | 2008/03/20 |
| [Spring] 스프링 MVC를 이용한 웹 요청 처리 (4) | 2008/03/13 |
| [Spring] Bean과 BeanFactory의 후처리 (8) | 2008/02/12 |
| [Spring] 자동 묶기(Autowire) (2) | 2008/02/12 |
| [Spring] 세터 주입(Setter Injection)의 대안 (5) | 2008/02/05 |
| [Spring] 빈 묶기(Bean wiring) (2) | 2008/02/05 |
| [Spring] 스프링 컨테이너의 두 종류 (0) | 2008/02/05 |
| [Spring] Spring 환경설정 (4) | 2008/01/28 |
[Spring] 세터 주입(Setter Injection)의 대안
Posted at 2008/02/05 14:28// Posted in 나만의 작업/Spring세터 주입(Setter Injection)의 대안 - 생성자 주입(Constructor Injection)
세터 주입은 빈 특성을 설정하고 묶을 수 있는 직관적인 방법이지만, 한 가지 단점은
변경될 수 있는 모든 특성이 세터 메소드를 통해서 사용할 수 있다고 가정하는 것에 있다. 하지만 빈이 이와 같은 방식으로 작동하기를 원하지 않을 때,
이런 유형의 빈이 인스턴스화될 때에는 어떤 특성도 설정될 수 없으며, 따라서 빈이 유효하지 않은 상태로 있을 가능성이 있다.
어떤 특성들은 빈이 생성될 때 한 번만 설정되고 그 이후에는 변경될 수 없도록 만들고 싶은 경우도 있다.
이는 세터를 통해 모든 특성을 공개하는 경우에는 곤란해진다.
대안은 일부 특성들은 생성자 를 통해 설정될 수 있도록 빈을 설계하는 것이다.
DAO의 DataSource와 같이 반드시 설정돼야 하고 변경되어서는 안 되는 특성이 있는 경우에 특히 유용
생성자 주입은, 어떤 특성을 설정하지 않고서는 인스턴스를 만들 수 없을 때,
'나만의 작업 > Spring' 카테고리의 다른 글
| [Spring] 스프링에서 VelocityTools 환경설정 (2) | 2008/03/20 |
|---|---|
| [Spring] 스프링 MVC를 이용한 웹 요청 처리 (4) | 2008/03/13 |
| [Spring] Bean과 BeanFactory의 후처리 (8) | 2008/02/12 |
| [Spring] 자동 묶기(Autowire) (2) | 2008/02/12 |
| [Spring] 세터 주입(Setter Injection)의 대안 (5) | 2008/02/05 |
| [Spring] 빈 묶기(Bean wiring) (2) | 2008/02/05 |
| [Spring] 스프링 컨테이너의 두 종류 (0) | 2008/02/05 |
| [Spring] Spring 환경설정 (4) | 2008/01/28 |
| [Spring] Hitting the database (8) | 2007/11/04 |
[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"
프로토타입 빈을 정의하는 것이 유리할 때
프로토타입을 정의한다는 것은 실제 하나의 빈을 정의하는 것이 아닌, 청사진을 정의한다는 의미다. 그 다음엔 그 청사진을 바탕으로 빈들이 생성될 것이다.
프로토타입 빈은, 빈을 요청할 때마다 컨테이너가 빈의 유일한 인스턴스를 제공하기 원하면서도 그 빈의 하나 이상의 특성을 스프링을 통해 설정하고자 할 경우에 유용
프로토타입으로 정의
빈 의 이름을 사용해 getBean()을 호출할 때마다 프로토타입의 새로운 인스턴스가 생성된다. 이로 인해 데이터베이스나 네트워크 연결과 같은 제한된 자원을 사용하는 빈의 경우에는 적합하지 않다. 최소한 새로운 인스턴스가 생성될 때마다 약간의 성능 저하를 겪을 수 있기 때문에, 절대적으로 필요한 경우에만 프로토타입으로 빈을 정의하자.
dW문서 'Spring 2.0: 요란스럽지 않은 진화의 흐름' 내용 중
Spring의 기반을 이루는 IoC 컨테이너에서는 앞서 언급한 XML 설정 이외에 빈(bean)의 스코프(scope)가 추가된 것이 주요 개선 사항이다.
Singleton과 prototype으로만 존재하던 스코프에 request, session 및 global session 스코프가 추가되었고, 사용자가 정의한 스코프를 사용할 수도 있다. 이러한 개선은 개발자가 직접 HTTP Request나 Session을 다루는 일을 줄여주고, 웹 어플리케이션의 커뮤니케이션 불연속성 문제를 다소나마 해결해줄 것으로 보인다.
| Scope | Description |
|---|---|
|
Scopes a single bean definition to a single object instance per Spring IoC container. | |
|
Scopes a single bean definition to any number of object instances. | |
|
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. | |
|
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. | |
|
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는 빈이 컨테이너로부터 제거되기 직전에 호출될 메소드를 지정한다.
Example) 커넥션 풀링(connection pooling) 빈
public class MyConnectionPool{
public void initialize(){
//커넥션 풀 초기화
}
}
public void close(){
//연결 해제
}
}
빈의 정의는,
MyConnectionPool이 인스턴스화되자마자 initialize() 메소드가 호출,
빈이 컨테이너로부터 제거되기 직전에 close() 메소드를 호출
스프링은 또 다른 방법으로, InitializingBean과 DisposableBean이라는 동일한 역할을 하는 두개의 인터페이스를 제공한다.
InitializingBean 인터페이스는 afterPropertiesSet() 메소드 : 빈의 모든 특성이 설정된 후에 한 번 호출.
DisposableBean 인터페이스는 destroy () : 빈이 컨테이너로부터 제거될 때 호출
이 방법은 인터페이스를 구현하는 빈을 스프링 컨테이너가 자동으로 탐지하며, 별다른 설정없이도 메소드를 호출해준다(XML 손대지 않고) 하지만, 인터페이스를 구현하게 되면, 빈은 스프링의 API에 묶이게 되어 버린다.
빈을 초기화하고 소멸시킬 때 가능하다면 init-method와 destroy-method 정의에 의존하는게 좋은 방법이다. 스프링의 인터페이스를 사용할만한 유일한 경우는 스프링 컨테이너 안에서 특별하게 사용될 프레임워크 빈을 개발할 때뿐이다.
'나만의 작업 > Spring' 카테고리의 다른 글
| [Spring] 스프링에서 VelocityTools 환경설정 (2) | 2008/03/20 |
|---|---|
| [Spring] 스프링 MVC를 이용한 웹 요청 처리 (4) | 2008/03/13 |
| [Spring] Bean과 BeanFactory의 후처리 (8) | 2008/02/12 |
| [Spring] 자동 묶기(Autowire) (2) | 2008/02/12 |
| [Spring] 세터 주입(Setter Injection)의 대안 (5) | 2008/02/05 |
| [Spring] 빈 묶기(Bean wiring) (2) | 2008/02/05 |
| [Spring] 스프링 컨테이너의 두 종류 (0) | 2008/02/05 |
| [Spring] Spring 환경설정 (4) | 2008/01/28 |
| [Spring] Hitting the database (8) | 2007/11/04 |
-
iolo2008/02/05 19:29 [Edit/Del] [Reply]singleton="false"라고 쓰는 방식은 deprecated임다.
scope="prototype"이라고 쓰는 방식으로 바뀌었습니당~
[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으로 설정)
'나만의 작업 > Spring' 카테고리의 다른 글
| [Spring] 스프링에서 VelocityTools 환경설정 (2) | 2008/03/20 |
|---|---|
| [Spring] 스프링 MVC를 이용한 웹 요청 처리 (4) | 2008/03/13 |
| [Spring] Bean과 BeanFactory의 후처리 (8) | 2008/02/12 |
| [Spring] 자동 묶기(Autowire) (2) | 2008/02/12 |
| [Spring] 세터 주입(Setter Injection)의 대안 (5) | 2008/02/05 |
| [Spring] 빈 묶기(Bean wiring) (2) | 2008/02/05 |
| [Spring] 스프링 컨테이너의 두 종류 (0) | 2008/02/05 |
| [Spring] Spring 환경설정 (4) | 2008/01/28 |
| [Spring] Hitting the database (8) | 2007/11/04 |
-
-
-
-
2007/11/07 09:37 [Edit/Del] [Reply]내가 이런데 댓글 안 다는거 알지?
K군 표현에 의하면 전락한 개발자라... ㅋㅋ
타오를때 열심히 해라~ 그래야 MIT도 가고 스탠퍼드도 가고 버클리도 가고 하니까~
5회 스프링 프레임웍 사용자 모임에 다녀왔습니다.
Posted at 2007/10/28 22:34// Posted in 나만의 작업스프링 프레임웍에 대한 세미나를 1회때인가, 스프링 소개와 IoC할때 가고, 정말
오랫만에 참여한지라 알아들을 수 있을 것인가, 염려와 함께 도곡역으로 향하였습니다.
장소는 도곡역 IBM 온디맨드 홀에서 열렸는데, 입구부터 백기선 님이 안내를 해주시더군요.국민대에서 할때 보다 훨씬 찾기 쉽고 더 집중이 잘 된 장소더군요^^
(차분하고, 듬직(?)하신 목소리로 너무 어렵지 않게 머릿속에 잘 들어왔습니다. )
Spring Web Flow (SWF) is an emerging module of The Spring Framework. The module is part of Spring’s web application development stack, which includes Spring MVC.
왜 ? 필요한가,?
servlet에서 scope단위는 request, session, application이 있는데,
request는 하나의 action요청에 관해서 scope가 너무 좋고,
session은 너무 넓다. 이것을 하나의 작은 묶음으로 처리하고 싶은데,
그럴만한 scope가 없다.
=> 상태정보유지와 관리(Flow : 하나의 task등을 재활용하기를 원한다.)
개개의 action은 여러 view를 통해 함께 chain되는데 action URL은
"back"이나 "submit'등과 같은 다른 처리를 하는 이벤트에 관해 각 view에
하드코딩이 된다.
Spring MVC는 두개의 controller인 SimpleFormController와
AbstractWizardFormController를 제공하는데 controller에 여전히 하드코딩을
해야한다.
Spring Web Flow의 Advantage
- Flow와 navigation을 완벽하게 control
Controller를 사용하지 않고 XML 파일로 정의하여 사용하고 Free navigation (페이지가 독립적인 단위라서, blog나 wikipedia에서처럼 simple URL로 접근해도 해당 정보를 보는데
전혀 지장이 없을경우, http://en.wikipedia.org/wiki/Spring 식으로 접근가능) 을
쓰려고 할때는 Web Flow가 필요없지만 어떤 제약을 많이 주고 싶은 경우(쇼핑몰 홈페이지에서 반드시 상품을 선택하고, 결제페이지를 넘어간다거나 할때) 사용하면 좋다.
- Server의 메모리 릭 해결(자동화된 상태관리)
- 모듈화된 Flow와 상태관리를 하고 싶을 때
XML로 정의된 Flow만 정의하면 되고,
컨트롤의 흐름,상태, 어디에서 시작해서 어디까지 끝날 것인지(scope)등
Flow의 상태를 유지할 수 있다.
- The page flow in a web application is clearly visible by looking at the corresponding web flow definition (in an XML file or Java class).
- Web flows are designed to be self contained. This allows you to see a part of your application as a module you can reuse in multiple situations.
- Web flows capture any reasonable page flow in a web application always using the same consistent technique. You're not forced into using specialized controllers for very particular situations.
- Finally, a web flow is a first-class citizen with a well-defined contract for use. It has a clear, observable lifecycle that is managed for you automatically. Simply put, the system manages the complexity for you and as a result is very easy to use.
http://www.theserverside.com/tt/articles/article.tss?l=SpringWebFlow
* XML파일을 Spring IDE를 이용하여 state Diagram으로 그려주면
자동으로 XML파일로 만들어준다. 이 부분이 가장 Happy하다. +_+
안영회님은 주로 개념과 흐름을 설명해주시고, 백기선님이 코드설명과
라이브코딩을(하지만, 정말 라이브코딩은 아니었다는, ^^ eclipse의 template기능 +_+) 오고가는 대화속의 훈훈함이 느껴졌습니다. 머릿속에도 쏙쏙 들어왔다는,,
Acegi Security is a powerful, flexible security solution for enterprise software, with a particular emphasis on applications that use Spring. Using Acegi Security provides your applications with comprehensive authentication, authorization, instance-based access control, channel security and human user detection capabilities.
Spring Acegi Tutorial :
http://www.tfo-eservices.eu/wb_tutorials/media/SpringAcegiTutorial/HTML/SpringAcegiTutorial-1_1-html.html
발표시나리오 :
http://younghoe.info/663
일이 있어서 끝까지 듣지는 못하여, 정리를 하지 못했습니다.
안영회님 블로그에 올라와 있는, 그림만 보아도 Filter들이 무슨일을 벌이고 처리하는지
대략알수 있다는 무책임한 말로 후기를 끝냅니다. +_+
다음번엔 무슨 주제가 기다릴까요.. 또 가고싶습니다!ㅋㅋ
--------------------------------------------------------------------------------------------------------------------
이 글에 대한 Resource :
http://www.theserverside.com/tt/articles/article.tss?l=SpringWebFlow
http://younghoe.info/663
'나만의 작업' 카테고리의 다른 글
| J2EE의 소프트웨어 디자인 원칙 (8) | 2008/01/17 |
|---|---|
| 티스토리에서 Syntaxhighlighter를 이용하기 (12) | 2007/12/04 |
| XML to JSON (6) | 2007/11/24 |
| 구글꺼야? SearchMash (16) | 2007/10/30 |
| 5회 스프링 프레임웍 사용자 모임에 다녀왔습니다. (10) | 2007/10/28 |
| Google Developer Night에 다녀와서,, (14) | 2007/10/17 |
| 다음(Daum) 검색창에서 "@버리"를 쳐보세요 (16) | 2007/10/11 |
| 2007 JCO 오픈소스 컨퍼런스 (10) | 2007/10/02 |
| 일상을 적는 서비스 "oladay" (10) | 2007/09/21 |
-
seattle2007/10/29 09:25 [Edit/Del] [Reply]전 개발자이고 쥐뿔도 모르면서 이런거엔 관심도 없고.. 아무래도 길을 잘못든거 같아요 ㅋㅋ
그래도 꾸역꾸역 버티는거 보면 신기하기도 하고요 ㅋ -
-
-
-
2007/10/29 13:33 [Edit/Del] [Reply]와... 포스팅의 난이도가 가면 갈수록 어려워지는데요 @_@
저는 이쪽저쪽 깨작거리다(?) 이도 저도 안되고 있는 중인데;;
한 분야로 쭉 직진하시는 모습이 아름다우십니다 ^^


