Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

스프링 프레임워크

예전에 Spring Framework 관련 직원 교육을 위해서 작성한 문서입니다.

  • Loggen Sie sich ein, um Kommentare anzuzeigen.

스프링 프레임워크

  1. 1. Enterprise Java Framework “Spring Framework” 2010.05.27 장윤기 (yoonki.chang@gmail.com)
  2. 2. 목차 1. Spring Framework 개요 2. Spring IoC 3. Spring AOP 4. Data Access 5. Transaction Management 6. Spring MVC 2
  3. 3. 1 Spring Framework 개요 1.1 Spring Framework이란? 1.2 Spring Framework 구성 1.3 Spring Framework의 장점 1.4 Spring 사용 시나리오 1.5 Spring Packages 1.6 Spring IDE 3
  4. 4. 1.1 SPRING FRAMEWORK이란? • A lightweight framework which addresses various tiers in a J2EE application. – Presentation layer: Integrates with Struts to initialize action classes – Business layer: Lightweight IoC container with support for AOP-driven interceptors and transaction. – Persistence layer – DAO template support for Hibernate, SQLMaps and JDBC – Factory implementation to abstract and integrate various other facets of enterprise applications like E-mails, JMS, WebServices, etc. • Helps integrates tiers together using XML configuration instead of hard-coding. • Substantially reduces code, speeds up development, facilitates easy testing and improves code quality. 4
  5. 5. 1.2 SPRING FRAMEWORK 구성 • SPRING FRAMEWORK은 여러 개의 단위로 구성 되어 있으며 각 각의 필요에 따라 개별적으로 혹은 통합해서 사용할 수 있다. 5
  6. 6. 1.3 SPRING FRAMEWORK의 장점 • Not a J2EE container. Doesn’t compete with J2EE app servers. Simply provides alternatives. • POJO-based, non-invasive framework which allows a la carte usage of its components. • Promotes decoupling and reusability • Reduces coding effort and enforces design discipline by providing out-of-box implicit pattern implementations such as singleton, factory, service locator etc. • Removes common code issues like leaking connections and more • Support for declarative transaction management • Easy integration with third party tools and technologies. 6
  7. 7. 1.4 SPRING 사용 시나리오 • Following are the typical usage scenarios for Spring – Presentation layer • Integrates with Struts to initialize action classes and its dependencies. • Facilitates presentation-tier testing – Business layer (Service Layer) • Integrates with EJBs • Provides integration with components using IoC. • Transaction (declarative and programmatic) – Persistence layer (Data Access Layer) • DAO pattern implementation • Template support for Hibernate, iBatis DataMapper and JDBC • Transaction management, Exception translation, connection management. – General • Email, JNDI, WebServices 7
  8. 8. 1.5 SPRING Packages • The Spring Framework 2.5 requires JDK 1.4.2 and J2EE 1.3 (Servlet 2.3, JSP 1.2, JTA 1.0, EJB 2.0). JDK 1.6 is required for building the framework; for the full build including all aspects, AspectJ is required as well • Integration is provided with Log4J 1.2, CGLIB 2.1, AspectJ 1.5/1.6, Commons Attributes 2.2, JCA 1.0/1.5, JMX 1.2, Hibernate 3.1/3.2, TopLink 10/11, JDO 2.0/2.1, JPA 1.0, iBATIS SQL Maps 2.3, Hessian 2.1/3.1, JAX-RPC 1.1, JAX-WS 2.0/2.1, Quartz 1.5/1.6, EHCache 1.3/1.4, Commons FileUpload 1.2, Velocity 1.5, FreeMarker 2.3, JasperReports 1.3/2.0, JSTL 1.0/1.1, JSF 1.1/1.2, Struts 1.2/1.3, Tiles 1.2/2.0, etc. 8
  9. 9. 1.5 SPRING Packages • Distribution Packages 구분 내용 ~-2.5.x.zip • "dist" contains the Spring binary jar files ~-2.5.x-withdocs.zip • "dist" contains the Spring binary jar files, as well as corresponding source jars • "docs" contains the Spring reference documentation in PDF and HTML format, as well as the complete API javadocs ~-2.5.x-withdependencies.zip • "dist" contains the Spring binary jar files, as well as corresponding source jars • "docs" contains the Spring reference documentation in PDF and HTML format, as well as the complete API javadocs • "lib" contains all third-party libraries needed for building and/or running • "src" contains the general Java source files for the framework • "mock" contains the general Java source files for Spring's mock and testing support classes • "test" contains the general Java source files for Spring's test suite • "tiger/src" contains the JDK-1.5-specific Java source files • "tiger/mock" contains the JDK-1.5-specific Java source files for Spring's mock and testing support classes • "tiger/test" contains the JDK-1.5-specific Java source files for Spring's test suite • "aspectj/src" contains the AspectJ-specific source files for the framework • "aspectj/test" contains the AspectJ-specific source files for Spring's test suite • "samples" contains various demo applications 9
  10. 10. 1.5 SPRING Packages • spring.jar library does not include spring-webmvc*.jar 구분 내용 spring-aop.jar • all the classes you need to use Spring’s AOP features within your application spring-beans.jar • all of Spring’s dependency injection (IoC) spring-context.jar • code needed to build the Spring application context spring-context-support.jar • utility Spring code—this means caching, instrumentation, e-mail and scheduling support, and scripting languages support. spring-core.jar • the core files of the Spring Framework: it deals with annotations, enumerations, task execution, resource loading, and other utilities and exceptions spring-jdbc.jar • code for the JDBC support classes, namely the JdbcTemplate and JdbcDaoSupport classes spring-jms.jar • code for JMS spring-orm.jar • the files needed for object-relational mapping (ORM) tools spring-test.jar • support code to write unit and integration tests using the Spring Framework spring-tx.jar • support for core data access exceptions and transaction technologies spring-web.jar • code for the Spring web application support (utilities, binders, multipart resolvers) spring-webmvc-portlet.jar • code needed to build portlet-based (rather than servlet-based) web applications spring-webmvc-struts.jar • code needed to use Spring with the Jakarta Struts Framework spring-webmvc.jar • the Spring MVC code 10
  11. 11. 2 Spring IoC 2.1 Invension of Control 이란? 2.2 Coupling 2.3 Dependency Injection 2.4 Bean Instantiation Modes 2.5 Bean Ineheritance 2.6 Spring BeanFactory 2.7 Spring ApplicationContext 11
  12. 12. 2.1 Invension of Control이란? • What is Invension? • Instead of objects invoking other objects, the dependant objects are added through an external entity/container. • Also known as the Hollywood principle – “don’t call me I will call you” • Prevents hard-coded object creation and object/service lookup. • Loose coupling • Helps write effective unit tests. 12
  13. 13. 2.1 Invension of Control이란? • Types of IoC • Dependency Lookup • Dependency Injection • Dependency Lookup : – Dependency lookup is the more traditional approach, and at first glance, it seems more familiar to Java programmers – DL is mandated by the Container – EJB 2.0 use DL and EJB 3.0 introduces DI • Dependency Injection : – Dependencies are “injected” by container during runtime. – Beans define their dependencies through constructor arguments or properties – Using DI, completely decoupled from the IoC Container – Spring can access EJB resources without lookup. 13
  14. 14. 2.2 Coupling • Tight Coupling • The implementation has been hard-coded into the class and cannot be changed except by recompilation • Test class cannot separate the behavior of the TightlyCoupled class from the behavior of SmtpImpl class • Cannot be replaced a differenct transport. Can be used smtp package com.apress.coupling; public class TightlyCoupled { private Transport transport = new SmtpImpl(); } public void sendMessage() { transport.send(); } 14
  15. 15. 2.2 Coupling • Loose Coupling – It does illustrate clearly the breaking of the dependency on the specific transport implementation – By allowing the implementation to be passed via the constructor, we allow alternative implementations to be passed in package com.apress.coupling; public class LooselyCoupled { private Transport transport; public LooselyCoupled(final Transport transport) { this.transport = transport; } } public void sendMessage() { transport.send(); } 15
  16. 16. 2.3 Dependency Injection • Although a Spring application can in principle be configured in any number of different ways, XML configuration files are by far the most common approach. • XML files offer us a better balance of flexibility, readability, verbosity, and expressiveness. • By default, XML bean definitions describe singletons • Injection type – Constructor Injection – Property Injection 16
  17. 17. 2.3 Dependency Injection • Constructor Injection (Construtor DI) – Some beans will not have a default constructor; these will need to be configured via the constructor <?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-2.0.xsd"> <bean id="smtp" class="com.apress.coupling.SmtpImpl" /> <bean id="soap" class="com.apress.coupling.SoapImpl" /> <bean id="looseSmtp" class="com.apress.coupling.LooselyCoupled"> <constructor-arg ref="smtp" /> </bean> <bean id="looseSoap" class="com.apress.coupling.LooselyCoupled"> <constructor-arg ref="soap" /> </bean> </beans> 17
  18. 18. 2.3 Dependency Injection • Use of constructor parameter injection is that the names of the parameters are not known at runtime • If the configuration is unambiguous (if the parameters are all of incompatible types, or if there is only one parameter), you can just list the appropriate constructor-arg elements • if there is an ambiguity in the types of parameters to the constructor you must provide an index attribute to each of the constructor arguments to identify <bean id="userAccount" class="com.apress.coupling.UserAccount"> <constructor-arg index="0" value="jdoe"/> <constructor-arg index="1" value="pa55word"/> </bean> 18
  19. 19. 2.3 Dependency Injection • Property Injection (Setter DI) – Typically, the properties take references to other beans, primitives, wrapped primitives, or strings. Any type can be provided as a parameter to a bean property, but the support for this set of common types is particularly comprehensive. – The properties are configured from XML as elements within the body of the bean element. They can be added in any order • Configured with a Single Property – It has a default constructor. <bean id=“refExample" class="com.apress.coupling.config.RefExample"> <property name="text" value="RefExample"/> </bean> 19
  20. 20. 2.3 Dependency Injection • Use a primitive type <property name="text" value="Hello World"/> • Use a reference type. Any type can be provided <property name="ref" ref="ref"/> • Use a list property <property name="list"> <list> <value>Mauve</value> <value>Puce</value> <value>Burnt Umber</value> <value>Beige</value> </list> </property> 20
  21. 21. 2.3 Dependency Injection • Use Collection type. (List, Map, Set …) <property name="map"> <map> <entry key="Mammal"> <list> <value>Cat</value> <value>Dog</value> <value>Human</value> </list> </entry> <entry key="Fish"> <list> <value>Minnow</value> <value>Shark</value> </list> </entry> </map> </property> 21
  22. 22. 2.3 Dependency Injection • Setter Injection vs Constructor Injection • Constructor injection – particularly useful when you absolutely must have an instance of the dependency class before your component is used • Setter Injection – If you want the component to expose its dependencies to the container but provide its own defaults, setter injection is usually the best way to accomplish this – it allows dependencies to be declared on an interface or an adapter class • Setter injection is the best choice, because it has the least effect on your code’s usability in non-IoC settings. • Many containers provide their own mechanism for doing this with setter injection 22
  23. 23. 2.4 Bean Instantiation Modes • By default, all beans in Spring are singletons • all dependent objects use the same instance <bean id="singleMe" class="java.lang.String" scope="singleton"> <constructor-arg type="java.lang.String" value="Singleton -- Jan Machacek"/> </bean> 구분 내용 prototype • Every call to the getBean() method returns a new instance of the bean request • Every call to the getBean() method in a web application will return a unique instance of the bean for every HTTP request. • This behavior is implemented in the WebApplicationContext session • Calls to the getBean() method will return a unique instance of the bean for every HTTP Session. • This scope is available in WebApplicationContext global session • The getBean() calls will return a unique instance of the bean for the global HTTP session in a portlet context. • This instantiation mode is only supported in WebApplicationContext 23
  24. 24. 2.5 Bean Inheritance • Need multiple definitions of beans that are the same type or implement a shared interface. This can become problematic if you want these beans to share some configuration settings but differ in <bean id="parent" class="com.apress.prospring2.ch03.inheritance.SimpleBean" abstract="true"> <property name="name" value="Jan Machacek"/> </bean> <bean id="bean1" class="com.apress.prospring2.ch03.inheritance.SimpleBean" parent="parent"> <property name="age" value="28"/> </bean> <bean id="bean2" class="com.apress.prospring2.ch03.inheritance.SimpleBean" parent="parent"/> 24
  25. 25. 2.6 Spring BeanFactory • BeanFactory is Spring’s DI Container • BeanFactory is core to the Spring framework – Lightweight container that loads bean definitions and manages your beans. – Configured declaratively using an XML file, or files, that determine how beans can be referenced and wired together. – Knows how to serve and manage a singleton or prototype defined bean – Responsible for lifecycle methods. – Injects dependencies into defined beans when served • Removes the need for ad-hoc singletons and factories 25
  26. 26. 2.7 Spring ApplicationContext • A Spring ApplicationContext allows you to get access to the objects that are configured in a BeanFactory in a framework manner. • ApplicationContext extends BeanFactory • Adds services such as international messaging capabilities. • Add the ability to load file resources in a generic fashion. • Several ways to configure a context: • XMLWebApplicationContext – Configuration for a web application. • ClassPathXMLApplicationContext – standalone XML application context • FileSystemXmlApplicationContext • Allows you to avoid writing Service Locators 26
  27. 27. 3 Spring AOP 3.1 AOP란? 3.2 AOP in Spring 3.3 Advice in Spring 3.4 Advisors and Pointcut in Spring 3.5 Pointcut Expression 3.6 Using the @Pointcut in XML 27
  28. 28. 3.1 AOP(Aspect-Oriented Programming)란? • Provides a non-intrusive solution to common OO limitation for easily implementing cross-cutting concerns. • Used effectively for functions such as declarative transaction management, declarative security, profiling, logging, etc. 28
  29. 29. 3.1 AOP(Aspect-Oriented Programming)란? • Cross-cutting concern : A problem that applies to parts of the object model that are not conveniently related, or that are not related in an object-oriented manner. For example, a problem that applies to method return values in general, rather than to the methods of a single class, is not an object-oriented problem as such. • JoinPoint : A well-defined point during the execution of your application. Typical examples of joinpoints include a call to a method, the method invocation itself, class initialization, and object instantiation • Pointcut : a collection of joinpoints that you use to define when advice should be executed. • Advice : The code that is executed at a particular joinpoint. • Aspects : An aspect is the combination of advice and pointcuts. This combination results in a definition of the logic that should be included in the application and where it should execute • Weaving : This is the process of actually inserting aspects into the application code at the appropriate point. 29
  30. 30. 3.1 AOP(Aspect-Oriented Programming)란? • Major AOP Tools 구분 AspectJ AspectWerkz JBossAOP Spring AOP 출시 2001 2002 2004 2004 Aspect 선언 전용코드 XML, Annotation XML, Annotation XML Advice 전용코드 자바 메소드 자바 메소드 자바 메소드 • 메소드, 생성자, Advice, Field Access, 인스턴스 • 메소드, 생성자, Advice, Field Access, 인스턴스 • 메소드, 생성자, Advice, Field Access, 인스턴스 • 메소드 • Signature, WildCard, Annotation • Signature, WildCard, Annotation • Signature, WildCard, Annotation • 정규식 Weaving • 컴파일 및 로딩 타임, 바이트 코 드 생성 • 컴파일 및 로딩 타임, 바이트 코 드 생성 • 런타임 인터셉션 및 Proxy • 런타임 인터셉션 및 Proxy IDE 지원 • Eclipse, JDeveloper, JBuilder, NetBeans • Eclipse, NetBeans • Eclipse • Eclipse JoinPoint Pointcu 매칭 30
  31. 31. 3.2 AOP in Spring • Spring’s AOP implementation as coming in two logical parts : – The AOP core, which provides fully decoupled, purely programmatic AOP functionality – the set of framework services that make AOP easier to use in your application • The core architecture of Spring AOP is based around proxies. When you want to create an advised instance of a class, you must use the ProxyFactory class – JDK Dynamic proxy – CGILIB proxy • Joinpoint in Spring – One of the more noticeable simplifications in Spring AOP is that it only supports one joinpoint type: method invocation 31
  32. 32. 3.3 Advice in Spring • Creating Advice in Spring • Before : you can perform custom processing before a joinpoint executes • After returning : executed after the method invocation at the joinpoint has finished executing and has returned a value • Around : a method interceptor. execute before and after method invocation. • Throws : executed after the method invocation returns but only if that invocation threw an exception • Introduction : a special types of interceptor. specify the implementation for methods that are being introduced by the advice • Advice Interface in Spring • • • • • Before : org.springframework.aop.MethodBeforeAdvice After returning : org.springframework.aop.AfterReturningAdvice Around : org.springframework.aop.MethodInterceptor Throws : org.springframework.aop.ThrowsAdvice Introduction : org.springframework.aop.IntroductionInterceptor 32
  33. 33. 3.3 Advice in Spring • Write “Hello World!” in AOP Application package com.apress.prospring.ch05.simple; public class MessageWriter { public void writeMessage() { System.out.print("World"); } } Around Advice package com.apress.prospring2.ch05.simple; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class MessageDecorator implements MethodInterceptor { public Object invoke(MethodInvocation invocation) throws Throwable { System.out.print("Hello "); Object retVal = invocation.proceed(); System.out.println("!"); return retVal; } } 33
  34. 34. 3.3 Advice in Spring • Write “Hello World!” in AOP package com.apress.prospring2.ch05.simple; Weaving import org.springframework.aop.framework.ProxyFactory; public class HelloWorldWeaver { public static void main(String[] args) { MessageWriter target = new MessageWriter(); // create the proxy ProxyFactory pf = new ProxyFactory(); pf.addAdvice(new MessageDecorator()); pf.setTarget(target); MessageWriter proxy = (MessageWriter) pf.getProxy(); } } // write the messages target.writeMessage(); System.out.println(""); proxy.writeMessage(); 34
  35. 35. 3.3 Advice in Spring • Before Advice package com.apress.prospring2.ch05.simple; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; import org.springframework.aop.framework.ProxyFactory; public class SimpleBeforeAdvice implements MethodBeforeAdvice { public static void main(String[] args) { MessageWriter target = new MessageWriter(); // create the proxy ProxyFactory pf = new ProxyFactory(); pf.addAdvice(new SimpleBeforeAdvice()); pf.setTarget(target); MessageWriter proxy = (MessageWriter) pf.getProxy(); // write the messages proxy.writeMessage(); } } public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("Before method: " + method.getName()); } 35
  36. 36. 3.3 Advice in Spring • After Returning Advice package com.apress.prospring2.ch05.simple; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.framework.ProxyFactory; public class SimpleAfterReturningAdvice implements AfterReturningAdvice { public static void main(String[] args) { MessageWriter target = new MessageWriter(); // create the proxy ProxyFactory pf = new ProxyFactory(); pf.addAdvice(new SimpleAfterReturningAdvice()); pf.setTarget(target); MessageWriter proxy = (MessageWriter) pf.getProxy(); // write the messages proxy.writeMessage(); } } public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println(""); System.out.println("After method: " + method.getName()); } 36
  37. 37. 3.3 Advice in Spring • Around Advice MessageDecorator class is a around advice 37
  38. 38. 3.3 Advice in Spring • Throw Advice package com.apress.prospring2.ch05.simple; public class ErrorBean { public void errorProneMethod() throws Exception { throw new Exception("Foo"); } } public void otherErrorProneMethod() throws IllegalArgumentException { throw new IllegalArgumentException("Bar"); } 38
  39. 39. 3.3 Advice in Spring • Throw Advice public class SimpleThrowsAdvice implements ThrowsAdvice { public static void main(String[] args) throws Exception { ErrorBean errorBean = new ErrorBean(); ProxyFactory pf = new ProxyFactory(); pf.setTarget(errorBean); pf.addAdvice(new SimpleThrowsAdvice()); ErrorBean proxy = (ErrorBean) pf.getProxy(); try { proxy.errorProneMethod(); } catch (Exception ignored) {} try { proxy.otherErrorProneMethod(); } catch (Exception ignored) {} } public void afterThrowing(Exception ex) throws Throwable { System.out.println("Generic Exception Capture"); System.out.println("Caught: " + ex.getClass().getName()); System.out.println("***n"); } } public void afterThrowing(Method method, Object[] args, Object target, IllegalArgumentException ex) throws Throwable { System.out.println("IllegalArgumentException Capture"); System.out.println("Caught: " + ex.getClass().getName()); System.out.println("Method: " + method.getName()); System.out.println("***n"); } 39
  40. 40. 3.4 Advisors and Pointcut in Spring • We used the ProxyFactory.addAdvice() method to configure advice for a proxy. this method delegates to addAdvisor() behind the scenes, creating an instance of DefaultPointcutAdvisor and configuring it with a pointcut that points to all methods • you may want to limit the methods to which an advice applies • By using pointcuts, you can configure the methods to which an advice applies, without needing to put this code inside the advice; this clearly increases the reuse value of the advice 40
  41. 41. 3.4 Advisors and Pointcut in Spring • Pointcut Interface • Pointcut을 구축하기 위한 최상위 인터페이스 public interface Pointcut { ClassFilter getClassFilter (); MethodMatcher getMethodMatcher(); } • ClassFilter Interface • Pointcut을 적용할 클래스에 대한 필터 적용 public interface ClassFilter { boolean matches(Class clazz); } 41
  42. 42. 3.4 Advisors and Pointcut in Spring • MethodMatcher Interface • Pointcut을 적용할 method 확인 • isRuntime 메소드를 통해 정적 혹은 동적 적용인지 결정 public interface MethodMatcher { boolean matches(Method m, Class targetClass); boolean isRuntime(); boolean matches(Method m, Class targetClass, Object[] args); } 42
  43. 43. 3.4 Advisors and Pointcut in Spring • Pointcut Example package com.apress.prospring2.ch05.staticpc; public class BeanOne { public void foo() { System.out.println("foo"); } } public void bar() { System.out.println("bar"); } 43
  44. 44. 3.4 Advisors and Pointcut in Spring • Pointcut Example package com.apress.prospring2.ch05.staticpc; import java.lang.reflect.Method; import org.springframework.aop.ClassFilter; import org.springframework.aop.support.StaticMethodMatcherPointcut; public class SimpleStaticPointcut extends StaticMethodMatcherPointcut { public boolean matches(Method method, Class cls) { return ("foo".equals(method.getName())); } } public ClassFilter getClassFilter() { return new ClassFilter() { public boolean matches(Class cls) { return (cls == BeanOne.class); } }; } 44
  45. 45. 3.4 Advisors and Pointcut in Spring • Pointcut Example package com.apress.prospring2.ch05.staticpc; public class StaticPointcutExample { public static void main(String[] args) { BeanOne one = new BeanOne(); BeanOne proxyOne; // create pointcut, advice, and advisor Pointcut pc = new SimpleStaticPointcut(); Advice advice = new SimpleAdvice(); Advisor advisor = new DefaultPointcutAdvisor(pc, advice); // create BeanOne proxy ProxyFactory pf = new ProxyFactory(); pf.addAdvisor(advisor); pf.setTarget(one); proxyOne = (BeanOne)pf.getProxy(); } } proxyOne.bar(); 45
  46. 46. 3.5 Annotation in Spring AOP • Sample Application for the Aspect • @Aspect : Spring to treat this bean as an aspect • @Around : Around advice with an AspectJ pointcut expression package com.apress.prospring.ch06.simple; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @Aspect public class LoggingAspect { @Around("execution(* com.apress.prospring.ch06.simple.TestBean.*(..))") public Object log(ProceedingJoinPoint pjp) throws Throwable { System.out.println("Before"); Object ret = pjp.proceed(); System.out.println("After"); return ret; } } 46
  47. 47. 3.5 Annotation in Spring AOP • Sample Application for the Aspect package com.apress.prospring.ch06.simple; public class TestBean { public void work() { System.out.println("work"); } } public void stop() { System.out.println("stop"); } 47
  48. 48. 3.5 Annotation in Spring AOP • Sample Application for the Aspect • Using ClassPathXmlApplicationContext package com.apress.prospring.ch06.simple; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class LoggingAspectDemo { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( "ataspectjdemo1-context.xml"); TestBean testBean = (TestBean) ac.getBean("test"); testBean.work(); testBean.stop(); } } 48
  49. 49. 3.5 Annotation in Spring AOP • Sample Application for the Aspect • ApplicationContext configuration file <?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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="test" class="com.apress.prospring.ch06.simple.TestBean" /> <bean class="com.apress.prospring.ch06.simple.LoggingAspect" /> <aop:aspectj-autoproxy /> </beans> 49
  50. 50. 3.5 Pointcut Expression • There are ten types of pointcut expressions; each type has its specific syntax – execution : AspectJ execution syntax • execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? namepattern(param-pattern) throws-pattern?) – within : formal syntax is far simpler than the syntax of the execution expression • within(declaring-type-pattern) – target : matching type of bean • target(ClassName) – args : matching method argument’s type • args(type-pattern? (, type-pattern)*); 50
  51. 51. 3.6 Using the @Pointcut in XML • Pointcut in XML Configuration <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=http://www.springframework.org/schema/beans …> <bean id="test" class="com.apress.prospring2.ch06.simple.TestBean2"> <property name="simpleBean" ref="simple"/> </bean> <bean id="simple" class="com.apress.prospring2.ch06.simple.SimpleBean"/> <aop:config> <aop:pointcut id="allServiceMethods" expression="execution(* com.apress.prospring2.ch16.services.*.*(..))"/> <aop:advisor advice-ref="tx-advice" pointcut-ref="allServiceMethods"/> </aop:config> <bean id="transactionManager" class="com.apress.prospring2.ch06.simple.NoopTransactionManager"/> <tx:advice id="tx-advice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> </beans> 51
  52. 52. 4 Spring MVC 4.1 Spring MVC란? 4.2 Spring MVC 사용 준비 4.3 Context Loader 적용 4.4 Dispatcher Servlet 4.5 Mapping Dispatcher URLs 4.6 Configuring a Controller 4.7 Configuring a View Resolver 4.8 Filters and Interceptors 52
  53. 53. 4.1 Spring MVC란? • MVC model 1 architecture • MVC model 2 architectue 53
  54. 54. 4.1 Spring MVC란? • Model : the domain-specific representation of the data that is involved in your application • View : a representation of the data in the model • Controller : updates the model in reaction to events received from the user, and causes the appropriate view for the model to be displayed or updated • Spring provides its own MVC frameworks : Spring MVC & Spring WebFlow • Spring MVC supports allows us to build flexible application using MVC model two 54
  55. 55. 4.2 Spring MVC 사용 준비 • Spring MVC 적용 절차 • • • • • Declare a Context Loader Listener or Context Loader Servlet Configuring the Dispatcher Servlet Mapping Dispatcher URLs to Controller Class Configuring a Controller Configuring a View Resolver • 설정 파일 기준의 절차 • web.xml : Spring Framework 인식 • applicationContext.xml : IoC (Service, DAO …) • ui-mapping.xml : View Mapping 55
  56. 56. 4.3 Context Loader 적용 • Web Application이 Spring 관련 설정 정보를 인식 할 수 있도록 적용. 최초 로딩 되는 부분임 <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> Servlet 2.3 이상 <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/conf/applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>context</servlet-name> <servlet-class> org.springframework.web.context.ContextLoaderServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> 56 Servlet 2.3 이하
  57. 57. 4.4 Dispatcher Servlet • Dispatcher Servlet • It will create its own private application context • It dispatches incoming web requests to a URL mapping bean, which in turn determines which Spring controller will handle the request. <servlet> <servlet-name>action</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/conf/ui*.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> 57
  58. 58. 4.5 Mapping Dispatcher URLs • Dispatcher Servlet loads HandlerMapping from its own context file • The mapping converts all incoming URLs into invocations of the appropriate controller, so there cannot be two different handler mappings <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="intercepterName"/> </list> </property> <property name="mappings"> <map> <entry key="/login.do" value-ref="loginHandler"/> <entry key="/accessDenied.do" value-ref="accessDeniedHandler"/> <entry key="/admin.do" value-ref="adminUserListController"/> <entry key="/admin/list.do" value-ref="adminUserListController"/> <entry key="/admin/view/**.do" value-ref="adminUserViewController"/> </map> </property> <property name="defaultHandler" ref="defaultHandler"/> </bean> 58
  59. 59. 4.5 Mapping Dispatcher URLs • All the paths are relative. When dispatchers is mapped to the root of its application context. • A default handler can be specified that will be used to handle URLs that are the responsibility of this dispatcher but don’t match any of the explicit mappings. • SimpleUrlHandlerMapping allows you to specify wildcards, allowing multiple paths with the same prefix to be passed to the same controller without tedious enumeration of the pathnames. • Wildcards – ? : matches any single character – * : matches any series of characters or no character – ** : matches zero or more directories in a path. Regardless of any additional / delimiters that might appear within it 59
  60. 60. 4.5 Mapping Dispatcher URLs • HandlerMapping Implementations 구분 설명 BeanNameUrlHandlerMapping • The bean name is identified by the URL. If the URL were /product/index.html, the controller bean ID that handles this mapping would have to be set to /product/index.html. This mapping is useful for small applications, as it does not support wildcards in the requests. SimpleUrlHandlerMapping • This handler mapping allows you to specify in the requests (using full names and wildcards) which controller is going to handle the request ControllerClassNameHandlerM apping • This handler mapping is part of the convenience over configuration approach introduced with Spring 2.5. It automatically generates URL paths from the class names of the controllers. 60
  61. 61. 4.6 Configuring a Controller • The controller is the core of the presentation logic for Spring MVC. • An incoming request will be received by the dispatcher servlet. • A suitable controller will be identified from the URL handler mapping component, and the life cycle of the controller will then be invoked. • Spring support a controller interface and provides a number of useful superclasses – – – – – AbstractController UrlFilenameViewController ParameterizableViewController MultiActionController Command Controllers 61
  62. 62. 4.6 Configuring a Controller • Controller (interfaces) – We need to implement ModelAndView handleRequest(HttpServletRequest, HttpServletResponse). – Implementing the Controller interface is, in most cases, too much work public class IndexController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { response.getWriter().println("Hello, world"); return null; } } 62
  63. 63. 4.6 Configuring a Controller • AbstractController – It directly gives you access to ServletContext, WebApplicationContext, ApplicationContext, Log, and MessageSourceAccessor public class IndexController extends AbstractController { protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { setCacheSeconds(10); response.getWriter().println("Hello, world at " + ? System.currentTimeMillis()); return null; } } 63
  64. 64. 4.6 Configuring a Controller • ModelAndView 64
  65. 65. 4.6 Configuring a Controller • UrlFilenameViewController – A very simple subclass of AbstractController – Implements the handleRequestInternal method to return a new model with url name. <bean id="publicUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <value> /index.html=indexController /pindex.html=simpleViewController … </value> </property> </bean> <bean id=“simpleViewController" class=“org.springframework.web.servlet.mvc.UrlFilenameViewController"> </bean> 65
  66. 66. 4.6 Configuring a Controller • ParameterizableViewController – A very simple subclass of AbstractController – Implements the handleRequestInternal method to return a new model with a name set in its viewName property. <bean id="publicUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <value> /index.html=indexController /pindex.html=parametrizableIndexController … </value> </property> </bean> <bean id="parametrizableIndexController" class=“org.springframework.web.servlet.mvc.ParameterizableViewController"> <property name="viewName" value="/WEB-INF/jsp/product/index.jsp"/ > </bean> 66
  67. 67. 4.6 Configuring a Controller • MultiActionController – It is also a subclass of AbstractController, giving it access to all its properties and methods. – It provide as many implementations of public ModelAndView(HttpServletRequest, HttpServletResponse) – It can define multiple handler method in a controller – The methodNameResolver must be set to an implementation of MethodNameResolver public class ProductController extends MultiActionController { public ModelAndView view(HttpServletRequest request, HttpServletResponse response) throws Exception { response.getOutputStream().print("Viewing product " + request.getParameter("productId")); return null; } } 67
  68. 68. 4.6 Configuring a Controller • MultiActionController must be set to an implementation of MethodNameResolver <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" ...> <!-- other beans --> <bean id="productController" class="com.apress.prospring2.ch17.web.product.ProductController"> <property name="methodNameResolver" ref="productMethodNameResolver"/> </bean> <bean id="productMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver"> <property name="mappings"> <value> /product/view.html=view /product/v*.html=view </value> </property> </bean> </beans> 68
  69. 69. 4.7 Command Controller • The command controller allows a command object’s properties to be populated from the <FORM> submission • The command controller implementations expose a command object, which is (in general) a domain object – – – – AbstractCommandController : AbstractFormController : SimpleFormController : AbstractWizardFormController : 69
  70. 70. 4.8 File Upload & Download • FileUpload : MultipartRequest 70
  71. 71. 4.8 File Upload & Download • FileDownload 71
  72. 72. 4.9 Configuring a View Resolver • A ViewResolver is a strategy interface that Spring MVC uses to look up and instantiate an appropriate view based on its name and locale • Configuring a View Resolver • There are various view resolver in Spring • 일반적으로 JSP 사용하나 Velocity 등 다른 기법 적용 가능 • Configuring JSP <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> </bean> 72
  73. 73. 4.9 Configuring a View Resolver • Velocity and FreeMaker are templating languages with similar behavior and syntax • In some ways they are like JSPs, but unlike JSPs they are interpreted dynamically rather than being compiled by the application server into class files • Configuring Velocity <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <property name="resourceLoaderPath" value="/WEB-INF/velocity/"/> </bean> <bean id="viewResolver" class= "org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="cache" value="true"/> <property name="prefix" value=""/> <property name="suffix" value=".vm"/> </bean> 73
  74. 74. 4.9 Configuring a View Resolver • Configuring FreeMaker <bean id="freemarkerConfig“ class= "org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/freemarker/"/> </bean> <bean id="viewResolver“ class= "org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="cache" value="true"/> <property name="prefix" value=""/> <property name="suffix" value=".ftl"/> </bean> 74
  75. 75. 4.10 Filters and interceptors • Java EE filters provide the opportunity to intercept incoming requests and perform operations on them before the request is passed to the appropriate servlet for processing • Interceptors are closely related to mappings, as you can specify a list of interceptors that will be called for each mapping. • HandlerInterceptor implementations can process each request before or after it has been processed by the appropriate controller 75
  76. 76. 4.10 Filters and interceptors • You can implement two methods : – preHandle : execute before request controller – postHandle : execute after request controller public class BigBrotherHandlerInterceptor extends HandlerInterceptorAdapter { public void preHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // process the request } } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // process the request } 76
  77. 77. 4.10 Filters and interceptors • To use the interceptor, you create a URL mapping and interceptor bean definitions in the Spring application context <bean id="bigBrotherHandlerInterceptor" class="com.apress.prospring2.ch17.web.BigBrotherHandlerInterceptor"/> <bean id="publicUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="interceptors"> <list> <ref local="bigBrotherHandlerInterceptor"/> </list> </property> <property name="mappings"> <value> /index.html=indexController /product/index.html=productController /product/view.html=productController /product/edit.html=productFormController </value> </property> </bean> 77
  78. 78. 5 Data Access 5.1 Data Access in Spring 5.2 Configuring DataSource 5.3 Using JdbcDaoSupport 5.4 Using JdbcTemplate 78
  79. 79. 5.1 Data Access in Spring • Spring provides libraries to help you create ordinary JDBCbased data access, but it also provides some support for several Object Relational Mapping (ORM) tools. • Spring offers support for the following APIs and frameworks • • • • JDBC Support iBatis Support Hibernate Support Java Persistence API (JPA), Java Data Object (JDO), Common Clienter Interface (CCI), Oracle TopLink, etc 79
  80. 80. 5.1 Data Access in Spring • Although the various data access libraries supported by Spring have different implementations, they do tend to have similar usage patterns • Spring takes advantage of this by providing sets of tailored support classes to aid in the building of data access logic, and specifically to aid in building DAO implementations • When building a DAO for a supported database access mechanism, you will generally find that Spring provides helper classes to aid in your implementation. These usually include a template class and a DAO support class 80
  81. 81. 5.1 Data Access in Spring • Helper Classes for Database access framework Framework DAO Support Class Template Class CCI • CciDaoSupport • CciTemplate Hibernate • HibernateDaoSupport • HibernateTemplate JDBC • JdbcDaoSupport • JdbcTemplate Java Data Objects • JdoDaoSupport • JdoTemplate Java Persistence API • JpaDaoSupport • JpaTemplate iBatis SQL Maps • SqlMapClientDaoSupport • SqlMapClientTemplate Oracle TopLink • TopLinkDaoSupport • TopLinkTemplate 81
  82. 82. 5.2 Configuring DataSource • A DataSource is a JDBC interface that represents an alternative to DriverManager. • Because it is an interface, many different implementations exist, from simple ones that just use the JDBC driver to get a connection to advanced pooling implementations • Using Apache DBCP <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="..."> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@oracle.devcake.co.uk:1521:INTL"/> <property name="username" value="PROSPRING"/> <property name="password" value="x******6"/> </bean> </beans> 82
  83. 83. 5.2 Configuring DataSource • Using WAS DataSource <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>jdbc/FMSDS</value> </property> <property name="lookupOnStartup"> <value>false</value> </property> <property name="cache"> <value>true</value> </property> <property name="proxyInterface"> <value>javax.sql.DataSource</value> </property> </bean> • Using J2EE XML Schema <jee:jndi-lookup id="dataSource" jndi-name="jdbc/FMSDS"/> 83
  84. 84. 5.3 Using JdbcDaoSupport • If you use JdbcDaoSupport as superclass of your data access tier classes, you can access the JdbcTemplate and the DataSource 84
  85. 85. 5.3 Using JdbcDaoSupport • Configuring JdbcDaoSupport <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" ...> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@oracle.devcake.co.uk:1521:INTL"/> <property name="username" value="PROSPRING"/> <property name="password" value="x******6"/> </bean> <bean id="abstractJdbcDao" abstract="true" class="org.springframework.jdbc.core.support.JdbcDaoSupport"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="customerDao" class="com.apress.prospring2.ch09.dataaccess.jdbc.JdbcCustomerDao" parent="abstractJdbcDao"/> </beans> 85
  86. 86. 5.3 Using JdbcDaoSupport • JdbcDaoSupport implementation public class JdbcCustomerDao extends JdbcDaoSupport implements CustomerDao { private SelectCustomerById selectCustomerById; private static class SelectCustomerById extends SqlQuery { SelectCustomerById(DataSource ds) { super(ds, "select * from t_customer where id=?"); declareParameter(new SqlParameter(Types.INTEGER)); } } protected RowMapper newRowMapper(Object[] parameters, Map context) { return ParameterizedBeanPropertyRowMapper.newInstance(Customer.class); } @Override protected void initDao() throws Exception { this.selectCustomerById = new SelectCustomerById(getDataSource()); } } @SuppressWarnings({"unchecked"}) public List<Customer> getAll() { return getJdbcTemplate().query("select * from t_customer", ParameterizedBeanPropertyRowMapper.newInstance(Customer.class)); } 86
  87. 87. 5.4 Using JdbcTemplate • At the core of Spring JDBC support is the JdbcTemplate class. • The JdbcTemplate allows you to work directly with instances of the Statement, PreparedStatement, and CallableStatement classes. 87
  88. 88. 5.4 Using JdbcTemplate • JdbcTemplate.query : query for existing data public List<String> selectName(String domainId) throws DataAccessException { List<String> returnValue; StringBuilder strSQL = new StringBuilder(); strSQL.append("SELECT CONFIG_ID "); strSQL.append("FROM FMS_ACTIVATE_INFO "); strSQL.append("WHERE DOMAIN_ID = ? "); strSQL.append("GROUP BY CONFIG_ID "); JdbcTemplate jdbcTemplate = getJdbcTemplate(); RowMapper rowMapper = new RowMapper() { public Object mapRow(ResultSet result, int rownum) throws SQLException { String configId = result.getString("config_id"); return configId; } }; returnValue = jdbcTemplate.query(strSQL.toString(), new Object[] { domainId }, rowMapper); } return returnValue; 88
  89. 89. 5.4 Using JdbcTemplate • Query methods in JdbcTemplate 구분 설명 queryForInt • The result is expected to contain only one row and one column, whose value is converted to int and returned. queryForList • This executes the statement; the execution of the statement can return more than one row, but must return only one column. The elementType argument specifies the type of the elements in the returned List. queryForLong • Just like queryForInt, this executes the statement and returns the value in the first row and first column converted to long. queryForMap • This method executes the statement, which must not return more than one • row; it returns a Map containing the column name as the key and the column value as the value. queryForObject • This one executes a single-row–returning statement and then uses the RowMapper to convert the ResultSet to an Object. If you do not want to use a RowMapper implementation, you can use the Class requiredType argument, as long as the column’s requiredType is one that the ResultSet can return (Integer, Long, String, etc.). queryForRowSet • This method executes the statement that can return any number of rows and returns the result as a RowSet. You are responsible for closing the returned RowSet 89
  90. 90. 5.4 Using JdbcTemplate • JdbcTemplate.update : insert, update and delete data public int update(FmsAuthInfo entity) throws DataAccessException { StringBuilder strSQL = new StringBuilder(); strSQL.append("UPDATE FMS_AUTH_INFO "); strSQL.append("SET AUTH_CLASS_NAME = ?, "); strSQL.append(" VALIDATION = ?, "); strSQL.append(" UPDATE_DATE = ?, "); strSQL.append(" USER_ID = ? "); strSQL.append("WHERE DOMAIN_ID = ? "); entity.updateDate = new Timestamp(System.currentTimeMillis()); } int returnValue = 0; JdbcTemplate jdbcTemplate = getJdbcTemplate(); returnValue = jdbcTemplate.update(strSQL.toString(), new Object[] { entity.authClassName, entity.validation, entity.updateDate, entity.userId, entity.domainId }); return returnValue; 90
  91. 91. 5.4 Using JdbcTemplate • JdbcTemplate.batchUpdate : a performance improvement public int insert(final String group_id, final String[] role_id) throws DataAccessException { int returnValue = 0; JdbcTemplate jdbcTemplate = getJdbcTemplate(); BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter() { public void setValues(PreparedStatement stmt, int index) throws SQLException { String roleIdTemp = role_id[index]; stmt.setString(1, group_id); stmt.setString(2, roleIdTemp); } }; } public int getBatchSize() { return role_id.length; } int result[] = jdbcTemplate.batchUpdate( "insert into fms_rolemembership (group_id, role_id) values (?, ?)", setter); … 91
  92. 92. 6 Transaction Management 6.1 Transaction Management with Spring 6.2 Transaction Manager 6.3 Programmatic Transactions 6.4 Annotation-Based Transactions 6.5 Schema-Based Transactions 92
  93. 93. 6.1 Transaction Management with Spring • Choice of two transaction managers – DataSourceTransactionManager for Local Transactions : PlatformTransactionManager implementation for single JDBC data sources. Binds a JDBC connection from the specified data source to the thread, potentially allowing for one thread connection per data source – JtaTransactionManager for using container transactions manager : PlatformTransactionManager implementation for JTA, i.e. J2EE container transactions. Can also work with a locally configured JTA implementation. This transaction manager is appropriate for handling distributed transactions, i.e. transactions that span multiple resources, and for managing transactions on a J2EE Connector (e.g. a persistence toolkit registered as JCA Connector). • Choice of two transaction – Declarative (preferred); Declarations are in Spring context. – Programmatic; only for scenarios when declarative doesn’t work. Custom Spring API 93
  94. 94. 6.1 Transaction Management with Spring • Transactions are typically enabled at the business tier level and not in the DAO • Spring transactions are an alternative to EJB transactions; for both declarative and programmatic • Have to be enabled after disabling EJB CMT. No point in having both 94
  95. 95. 6.1 Transaction Management with Spring • Propagation Behavior Values 구분 설명 TransactionDefinition. PROPAGATION_REQUIRED • Spring will use an active transaction if it exists. If not, Spring will begin a new transaction TransactionDefinition. PROPAGATION_SUPPORTS • Spring will use an active transaction; if there is no active transaction, Spring will not start a new one TransactionDefinition. PROPAGATION_MANDATORY • Spring will use an active transaction; if there is no active transaction, Spring will throw an exception TransactionDefinition. PROPAGATION_REQUIRES_NEW • Spring will always start a new transaction. If an active transaction already exists, it is suspended. TransactionDefinition. PROPAGATION_NOT_SUPPORTED • Spring will not execute the code in an active transaction. The code always executes nontransactionally and suspends any existing transaction. TransactionDefinition. PROPAGATION_NEVER • This always executes nontransactionally even if an active transaction exists. It throws an exception if an active transaction exists. TransactionDefinition. PROPAGATION_NESTED • This runs in a nested transaction if an active transaction exists. If there is no active transaction, the code runs as if TransactionDefinition.PROPAGATION_REQUIRED is set. 95
  96. 96. 6.1 Transaction Management with Spring • Transaction Isolation Levels 구분 설명 TransactionDefinition. ISOLATION_DEFAULT • This is the default isolation level for an individual PlatformTransactionManager (ISOLATION_READ_COMMITTED for most databases). TransactionDefinition. ISOLATION_READ_UNCOMMIT TED • This is the lowest level of isolation; This transaction can see all changes other transactions perform even before they are committed. TransactionDefinition. ISOLATION_READ_COMMITTED • This is the default level in most databases; it specifies that other transactions cannot see the data modifications before this transaction completes. This means that at different points in this transaction, you can see different data as other transactions modify it. TransactionDefinition. ISOLATION_REPEATABLE_READ • More strict than ISOLATION_READ_COMMITTED, this isolation level ensures that if you select a data set in this transaction, you can select at least the same set again, even if other transactions modify the selected data. However, if another transaction inserts new data, you can select the newly inserted data. TransactionDefinition. ISOLATION_SERIALIZABLE • This is the most expensive and reliable isolation level; all transactions are treated as if they were executed one after another. 96
  97. 97. 6.2 Transaction Manager • Local Transactions : <bean id=“localTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource“ ref="springContainerDataSource" /> </bean> • JTA Transactions : (WAS Vendor dependency) <bean id="wsJtaTm" class="org.springframework.transaction.jta.WebSphereTransactionManagerFactoryBean"/> <bean id="distTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="transactionManager" ref="wsJtaTm" /> <property name="userTransactionName"><null /></property> </bean> 97
  98. 98. 6.3 Programmatic Transactions • You can use the PlatformTransactionManager directly public class ProgrammaticTxBankService extends BankServiceSupport implements BankService{ private PlatformTransactionManager transactionManager; public void transfer(AccountIdentity from, AccountIdentity to, BigDecimal amount) throws Throwable { TransactionDefinition transactionDefinition = new DefaultTransactionDefinition( TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus transactionStatus = this.transactionManager.getTransaction(transactionDefinition); } } ... try { doTransfer(from, to, amount); this.transactionManager.commit(transactionStatus); } catch (Throwable t) { this.transactionManager.rollback(transactionStatus); throw t; } 98
  99. 99. 6.3 Programmatic Transactions • Configuring Service Controller for Programmatic Transactions <?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.xsd"> <bean id="bankService" class="com.apress.prospring2.ch16.services.ProgrammaticTxBankService"> <property name="accountDao" ref="accountDao"/> <property name="transactionManager" ref="transactionManager"/> </bean> </beans> 99
  100. 100. 6.4 Annotation-Based Transactions • Using Annotation-Based AOP Transaction Management • Configuring for annotation transaction manager <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="bankService" class="com.apress.prospring2.ch16.services.DefaultBankService"> <property name="accountDao" ref="accountDao"/> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <aop:aspectj-autoproxy /> </beans> 100
  101. 101. 6.4 Annotation-Based Transactions • Declare transaction in source code @Transactional(readOnly=true, propagation=Propagation.PROPAGATION_SUPPORTS) public List<String> selectActivateName(String domainId) throws DataAccessException { List<String> returnValue = fmsActivateInfoDAO.selectActivateName(domainId); return returnValue; } @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public int insert(FmsActivateInfo entity) throws DataAccessException { int returnValue = fmsActivateInfoDAO.insert(entity); if(logger.isInfoEnabled()) { logger.info(entity); } return returnValue; } 101
  102. 102. 6.5 Schema-Based Transactions • Using XML AOP Transaction Management • The problem with Annotation-Based Transaction Management approach is that you have to repeat the @Transactional annotation for every transactional method <aop:config> <aop:pointcut id="allServiceMethods" expression="execution(* com.apress.prospring2.ch16.services.*.*(..))"/> <aop:advisor advice-ref=“txAdvice" pointcut-ref="allServiceMethods"/> </aop:config> <tx:advice id="txAdvice" transaction-manager=“transactionManager"> <tx:attributes> <tx:method name=“select*“ read-only=“true”/> <tx:method name=“insert*“ read-only=“false” propagation=“REQUIRED”/> <tx:method name=“update*“ read-only=“false” propagation=“REQUIRED”/> <tx:method name=“delete*“ read-only=“false” propagation=“REQUIRED”/> </tx:attributes> </tx:advice> 102