Introduction to spring


Published on

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Introduction to spring

  1. 1. Introduction to Spring Oded Nissan
  2. 2. Introduction to Spring • • • • • • Introduction About the Lecturer Topics Exercises Agenda Questions ? Copyright(c) Oded Nissan 2010
  3. 3. Introduction to Spring • • • • • • Introduction About the Lecturer Topics Exercises Agenda Questions ? Copyright(c) Oded Nissan 2010
  4. 4. Agenda • • • • • Spring architecture and overview Dependency Injection and the IOC Container Resources Spring AOP Summary Copyright(c) Oded Nissan 2010
  5. 5. Spring architecture and overview • Spring Introduction • Spring Architecture • The Spring Framework Components Copyright(c) Oded Nissan 2010
  6. 6. Dependency Injection and the IOC Container • • • • • What is dependency injection? IOC container overview Working with Spring beans Managing dependencies Advanced features Copyright(c) Oded Nissan 2010
  7. 7. Resources • • • • • Available Resource implementations The Resource Loader Injecting Resources ApplicationContext and Resources Resources and Wildcards Copyright(c) Oded Nissan 2010
  8. 8. Spring AOP • • • • • What is AOP ? AOP Concepts Spring AOP options Example Summary Copyright(c) Oded Nissan 2010
  9. 9. Spring architecture and overview Copyright(c) Oded Nissan 2010
  10. 10. Spring architecture and overview • Spring Introduction • Spring Architecture • The Spring Framework Components Copyright(c) Oded Nissan 2010
  11. 11. Resources • - the home of the Spring Framework. • – a hub for Spring resources. • t/spring-framework-reference/html/ - the Spring Framework reference documentation. • avadoc-api/ - Spring API docs. • ng/dashboard.action - Spring community wiki. Copyright(c) Oded Nissan 2010
  12. 12. Spring Introduction • What Is Spring ? – The Spring Framework is an open source application framework that aims to make JEE development easier. – Popular open source framework – Based on the dependency injection pattern – Developed by Rod Johnson in 2004 – Current version is 3.0 Copyright(c) Oded Nissan 2010
  13. 13. Why do we need Spring ? • • • • JEE is too complex and too tightly coupled. An alternative to the complex EJB technology. JEE is based on tools and code generators. Lightweight framework that does not need a full JEE server to run. • Better performance. • JEE is hard to unit test. Copyright(c) Oded Nissan 2010
  14. 14. Spring Principles • Spring is a non-invasive framework. • Spring provides a consistent programming model, usable in any environment • Spring aims to promote code reuse. • Spring aims to facilitate Object Oriented design in JEE applications • Spring aims to facilitate good programming practice, such as programming to interfaces, rather than classes Copyright(c) Oded Nissan 2010
  15. 15. Spring Principles • Spring promotes plugability • Spring facilitates the extraction of configuration values from Java code into XML or properties files. • Spring is designed so that applications using it are as easy as possible to test • Spring is consistent • Spring promotes architectural choice • Spring does not reinvent the wheel Copyright(c) Oded Nissan 2010
  16. 16. Spring Architecture • • • • Spring is designed as a modular framework. Modules as separate and not tightly coupled. Compatible with all application servers. Easy integration into JEE or stand alone Java applications. Copyright(c) Oded Nissan 2010
  17. 17. Spring Architecture Copyright(c) Oded Nissan 2010
  18. 18. Spring Usage Scenarios • One of the advantages of spring is that it’s not a “take it or leave it” framework. • Not all spring modules need to be used. • Spring modules can be easily integrated with other frameworks. • Spring also provides simplified APIs to JEE services. Copyright(c) Oded Nissan 2010
  19. 19. Full Spring Web application Copyright(c) Oded Nissan 2010
  20. 20. Spring as a Middle Tier Copyright(c) Oded Nissan 2010
  21. 21. Spring as a Remoting Framework Copyright(c) Oded Nissan 2010
  22. 22. Spring Framework Components • • • • • • IOC Container. Aspect Oriented Programming Framework. Data access abstraction. Transaction management. MVC web framework. Integration Copyright(c) Oded Nissan 2010
  23. 23. The IOC Container • The technology that Spring is most identified with is Inversion of Control, and specifically the Dependency Injection flavor of Inversion of Control. • Inversion of Control is best understood through the term the "Hollywood Principle," which basically means "Don't call me, I'll call you." • We will discuss IOC in detail later.. Copyright(c) Oded Nissan 2010
  24. 24. The IOC Container • The IOC Container is the core of Spring’s framework. • It is a container that supplies a factory to access and create Java Beans. • The Java beans contain application code which does not depend on the Spring framework. • The IOC container takes responsibility for object instantiation, it can also support important creational patterns such as singletons, prototypes, and object pools. Copyright(c) Oded Nissan 2010
  25. 25. Aspect Oriented Programming Framework • AOP enables us to capture the cross-cutting code in modules such as interceptors that can be applied declaratively wherever the concern they express applies — without imposing tradeoffs on the objects benefiting from the services. • Spring AOP allows the proxying of interfaces or classes. It provides an extensible pointcut model, enabling identification of which sets of method to advise Copyright(c) Oded Nissan 2010
  26. 26. Data access Abstraction. • Spring provides an abstraction layer over JDBC that is significantly simpler and less error-prone to use than JDBC when you need to use SQLbased access to relational databases. • The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, Hibernate and JDO. Using the ORM package you can use all those O/R-mappers in combination with all the other features Spring offers, such as the simple declarative transaction management feature mentioned previously. Copyright(c) Oded Nissan 2010
  27. 27. Data access Abstraction. • Spring provides support for sending and receiving JMS messages in a much simpler way than provided through standard JEE. • JMX support: Spring supports JMX management of application objects it configures. • The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream. Copyright(c) Oded Nissan 2010
  28. 28. Transaction management. • Spring supports one of the key features of the EJB model- declarative transactions: – With declarative transaction management, the transactional behavior of beans is managed by the container. – Declarative transaction management reduces the complexity of transactions for application developers and makes it easier to create robust transactional applications. Copyright(c) Oded Nissan 2010
  29. 29. Transaction management • Spring supports Declarative Transaction management through the use of AOP. • Spring’s transaction module can work with JTA transactions or local transactions using JDBC, JPA, Hibernate or JDO by simply adjusting the configuration files. Copyright(c) Oded Nissan 2010
  30. 30. MVC Web Framework. • Spring provides a web framework based on the Model-View-Controller (MVC) paradigm. • Spring MVC provides out-of-the-box implementations of workflow typical to web applications. It is highly flexible, allowing you to use a variety of different view technologies. It also enables you to fully integrate with your Spring-based, middle-tier logic through the use of the Dependency Injection Copyright(c) Oded Nissan 2010
  31. 31. The MVC Pattern • • • The Model View Controller pattern provides a clean separation between the presentation logic and business logic. The MVC pattern is the foundation of most web frameworks. Can be implemented by mixing Servlets JSPs and Java Beans. Copyright(c) Oded Nissan 2010
  32. 32. The MVC Pattern Copyright(c) Oded Nissan 2010
  33. 33. The MVC Pattern • • • • The view part of the MVC pattern is usually implemented using a JSP page. A Java Bean represents the model part. The controller is represented by a Servlet. Business logic is implemented by Java classes or EJBs that are invoked by the controller servlet. Copyright(c) Oded Nissan 2010
  34. 34. Integration • Spring supplies integration with various JEE technologies: – Web Services – EJB – JCA – JMX • Remoting framework over HTTP. • Task Execution and Scheduling. Copyright(c) Oded Nissan 2010
  35. 35. Summary • What did we discuss ? – Spring Introduction – Spring Architecture – The Spring Framework Components Copyright(c) Oded Nissan 2010
  36. 36. Questions ? Copyright(c) Oded Nissan 2010
  37. 37. Dependency Injection and the IOC Container Copyright(c) Oded Nissan 2010
  38. 38. Dependency Injection and the IOC Container • • • • • What is dependency injection? IOC container overview Working with Spring beans Managing dependencies Advanced features Copyright(c) Oded Nissan 2010
  39. 39. What is dependency injection? • Dependency Injection is a form of push configuration; the container "pushes" dependencies into application objects at runtime. • This is the opposite of traditional pull configuration, in which the application object "pulls" dependencies from its environment. Copyright(c) Oded Nissan 2010
  40. 40. What is dependency injection? • Also called Inversion of control and the Hollywood pattern (“Don’t call me I’ll call you”). • Dependency injection can be implemented with or without a framework. • The framework simplifies and automates the injection of dependencies. Copyright(c) Oded Nissan 2010
  41. 41. What is dependency injection? An example and discussion. • Copyright(c) Oded Nissan 2010
  42. 42. Advantages of Dependency Injection • Application classes are self-documenting, and dependencies are explicit • No lock-in to a particular framework, or proprietary code. • Greater flexibility in managing configurations. • Code focuses on application logic, rather than dependency management or infrastructure. • Unit testing is easier. Copyright(c) Oded Nissan 2010
  43. 43. Dependency Injection Frameworks • Some frameworks deal only with dependency injections. Some of the popular dependency injection frameworks (besides Spring): – Google Guice. – Pico Container – JMock – JEE 5 and JEE 6 provide limited dependency injection. Copyright(c) Oded Nissan 2010
  44. 44. IOC Container Overview • The IoC container and is responsible for instantiating, configuring, and assembling beans. • It gets its instructions on which objects to instantiate, configure, and assemble by reading configuration metadata. • The configuration metadata is represented in XML, Java annotations, or Java code. Copyright(c) Oded Nissan 2010
  45. 45. IOC Container Overview • The BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object. • ApplicationContext is a sub-interface of BeanFactory. It adds easier integration with Spring's AOP features; message resource handling (for use in internationalization), event publication; and application-layer specific contexts such as the WebApplicationContext for use in web applications. • Usually we will work with the Applicationcontext. Copyright(c) Oded Nissan 2010
  46. 46. IOC Container Overview Copyright(c) Oded Nissan 2010
  47. 47. IOC Container Overview The following is an example of a Spring XML configuration file: Each Bean has an id and a class attribute. The id attribute is a string that you use to identify the individual bean definition. The class attribute defines the type of the bean and uses the fully qualified classname. Copyright(c) Oded Nissan 2010
  48. 48. Instantiating a Container • The container can be instantiated with an XML file that can be either on a specific file system path,URL or the classpath. • We will usually prefer the classpath mechanism. Copyright(c) Oded Nissan 2010
  49. 49. Instantiating a Container Copyright(c) Oded Nissan 2010
  50. 50. IOC Container Configuration • Besides using several configuration files for the same container, configuration files can be included in other configuration files using the “import” tag: Copyright(c) Oded Nissan 2010
  51. 51. Working with Beans • Use the getBean() method on the container to retrieve beans. • You can also supply the class as a parameter and avoid the cast on the returned object: Copyright(c) Oded Nissan 2010
  52. 52. Instantiating Beans • To instantiate a bean, initialize the IOC container and call the getBean() method of the container to retrieve the bean: Copyright(c) Oded Nissan 2010
  53. 53. Working with Beans • Spring beans have the following properties: – – – – – – – – – – – id name class scope constructor args properties autowire mode init-method destroy-method lazy initialization dependency check Copyright(c) Oded Nissan 2010
  54. 54. Working with Beans • Beans are be identified with the “id” or “name” attributes. • The “id” attribute is a real XML id, so it can be validated by the XML parser for uniqueness. • However there are some limitation on the valid characters in an XML id. In that case the “name” attribute is an alternative. • The “id” tag is the preferred way of identifying beans. Copyright(c) Oded Nissan 2010
  55. 55. Using a Factory • Beans can also be instantiated using a factory. • You can define a bean with a static factory method. Use the class attribute to specify the class containing the static factory method and an attribute named factory-method to specify the name of the factory method. • Instantiation with an instance factory method invokes a non-static method of an existing bean from the container to create a new bean. Copyright(c) Oded Nissan 2010
  56. 56. Using a Factory • Using a static factory: • Using an instance factory: Copyright(c) Oded Nissan 2010
  57. 57. Working with Beans • Dependency injection comes with two flavors: – Setter based dependency injection- dependencies are injected using setter methods. – Constructor based dependency injection – dependencies are injected as parameters to the bean constructor. – We will usually prefer to use setter based dependency injection, since it is easier to maintain. Copyright(c) Oded Nissan 2010
  58. 58. Setter based Dependency injection • Initializing a bean using XML: • Retrieving the bean: Copyright(c) Oded Nissan 2010
  59. 59. Setter based Dependency injection • The bean class includes the appropriate getters and setters for the properties: Copyright(c) Oded Nissan 2010
  60. 60. Constructor based Dependency Injection • The argument is supplied to the constructor in the XML file. The appropriate constructor is defined in the bean: Copyright(c) Oded Nissan 2010
  61. 61. Constructor based Dependency Injection • Sometimes it is necessary to specify the argument types to prevent ambiguity. • If a bean has two constructors, one accepting a String and the other accepting an int, the container might not recognize which constructor we want to invoke. • The values specified as arguments or properties are converted from a string type to the correct type in the bean using Spring PropertyEditors. Copyright(c) Oded Nissan 2010
  62. 62. Constructor based Dependency Injection • For example, see the constructors of SampleBean: • And the XML definition: Copyright(c) Oded Nissan 2010
  63. 63. Constructor based Dependency Injection • In this case we need to specify the argument type to the container to prevent ambiguity: • We can also specify the argument position when the constructor has multiple arguments: Copyright(c) Oded Nissan 2010
  64. 64. Dependency Injection • Spring’s dependency injection framework allows injecting the following types: – Primitive values – References to other beans – Collections Copyright(c) Oded Nissan 2010
  65. 65. Dependency Injection • Injecting beans using method injection: Copyright(c) Oded Nissan 2010
  66. 66. Dependency Injection • Injecting beans using constructor injection: Copyright(c) Oded Nissan 2010
  67. 67. Collections Dependency Injection • You can use the <list>, <map> and <props> to inject collections into beans. Copyright(c) Oded Nissan 2010
  68. 68. Collections Dependency Injection • As of Spring 2.0, the container supports the merging of collections. An application developer can define a parent-style <list/>, <map/>, <set/> or <props/> element, and have child-style <list/>, <map/>, <set/> or <props/> elements inherit and override values from the parent collection. • The child collection's values are the result of merging the elements of the parent and child collections, with the child's collection elements overriding values specified in the parent collection. Copyright(c) Oded Nissan 2010
  69. 69. Collections Dependency Injection • Collections Merging: Copyright(c) Oded Nissan 2010
  70. 70. Exercise Copyright(c) Oded Nissan 2010
  71. 71. Injecting Empty Values • Spring can inject empty values using an empty string or a <null> element: Copyright(c) Oded Nissan 2010
  72. 72. Aliasing Beans • You can provide an alias name for an existing bean. • This is useful in case we need to use beans that exist in a different subsystem. • The bean is mapped from the name to the alias: Copyright(c) Oded Nissan 2010
  73. 73. Using idref • The <idref> tag is used to reference other beans. It is an alternative to the <ref> tag. • The referenced bean name should be passed in the <idref> tag. This allows the container to verify the dependencies at deploy time, rather than at runtime. Copyright(c) Oded Nissan 2010
  74. 74. Inner Beans • A <bean/> element inside the <property/> or <constructor-arg/> elements defines a socalled inner bean. • An inner bean is anonymous and is always of prototype scope. Copyright(c) Oded Nissan 2010
  75. 75. Depends On • Sometimes there is a dependency between beans that is indirect. For example, when one bean depends on another bean being initialized before its creation. • This dependency management is achieved by using the <depends-on> tag that can explicitly force one or more beans to be initialized before the bean using this element is initialized. Copyright(c) Oded Nissan 2010
  76. 76. Depends On • The <depends-on> tag can also specify several dependencies separated by commas. Copyright(c) Oded Nissan 2010
  77. 77. Lazy Initialization • Lazy initialization is used when we want to load bean properties on demand as they are accessed by the program. • This is usually used when initialization is a costly operation. • Spring supports lazy initialization of beans by using the “lazy-init=true” attribute of the <bean> element. Copyright(c) Oded Nissan 2010
  78. 78. Autowiring • Spring is able to use introspection of bean classes in the factory and perform autowiring of dependencies. • In autowiring, you leave the bean property or constructor argument undeclared (in the XML file), and Spring will use reflection to find the type and name of the property, and then match it to another bean in the factory based on type or name. Copyright(c) Oded Nissan 2010
  79. 79. Autowiring • Autowiring at the bean level is controlled via the use of the autowire attribute, which has five possible values: – No – no autowiring Bean properties and constructor arguments must be explicitly declared. – byName- Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. – byType- Autowire by matching type. if there is exactly one bean in the factory of the same type as the property, the property value is set as that other bean. If there is more than one bean in the factory matching the type, it is considered a fatal error and an exception is raised. Copyright(c) Oded Nissan 2010
  80. 80. Autowiring – constructor - Autowire the constructor by type. This works in essentially identical fashion to how byType works for properties, except that there must be exactly one matching bean, by type, in the factory for each constructor argument. – autodetect - Choose byType or constructor as appropriate. The bean is introspected, and if there is a default no-arg constructor, byType is used, otherwise, constructor is used. Copyright(c) Oded Nissan 2010
  81. 81. Autowiring Example Copyright(c) Oded Nissan 2010
  82. 82. Autowiring Limitations • Explicit dependencies in property and constructor-arg settings always override autowiring. • You cannot autowire so-called simple properties such as primitives, Strings, and Classes (and arrays of such simple properties). This limitation is by-design. Copyright(c) Oded Nissan 2010
  83. 83. Autowiring • Pros: – Less Spring configuration. – Configuration can be outdated. Autowiring will ensure that dependencies are up to date. • Cons: – Autowiring is less exact than explicit wiring. – Wiring information may not be available to tools that may generate documentation from a Spring container. – Does not provide the dependency documentation that explicit wiring does. Copyright(c) Oded Nissan 2010
  84. 84. Excluding a Bean from Autowiring • On a per-bean basis, you can exclude a bean from autowiring. In Spring's XML format, set the autowire-candidate attribute of the <bean/> element to false; the container makes that specific bean definition unavailable to the autowiring infrastructure. • You can also limit autowire candidates based on pattern-matching against bean names. The toplevel <beans/> element accepts one or more patterns within its default-autowire-candidates attribute. Copyright(c) Oded Nissan 2010
  85. 85. Exercise Copyright(c) Oded Nissan 2010
  86. 86. Bean Scopes • When you create a bean definition, you create a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you can create many object instances from a single recipe. • Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports five scopes, three of which are available only if you use a web-aware ApplicationContext. Copyright(c) Oded Nissan 2010
  87. 87. Bean Scopes Bean Scop Description Singleton Only one bean is created per container Prototype A bean is created with each bean request from the container Request A bean is created for each HTTP request. Session A bean is created for each HTTPSession Global-session Similar to session and applies only in the context of portlet-based web applications Copyright(c) Oded Nissan 2010
  88. 88. The Singleton Scope Copyright(c) Oded Nissan 2010
  89. 89. The Prototype Scope Copyright(c) Oded Nissan 2010
  90. 90. Singleton Beans with Prototype Dependencies • When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies are resolved at instantiation time. Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean. • Usually this is not what we want. We want to get a new prototype bean every time we request it from the singleton bean. Copyright(c) Oded Nissan 2010
  91. 91. Singleton Beans with Prototype Dependencies • One solution to this problem of a prototype bean in a singleton bean is to get the bean directly from the container. • However, that would make the bean container-aware and would break our dependency injection framework. • We can solve the problem a Spring mechanism called method injection. Copyright(c) Oded Nissan 2010
  92. 92. Method Injection • Lookup method injection is the ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container. • The Spring Framework implements this method injection by using bytecode generation from the CGLIB library to generate dynamically a subclass that overrides the method. Copyright(c) Oded Nissan 2010
  93. 93. Method Injection • We create the singleton bean, with the method that lookups the prototype bean as abstract. With the following signature: • We then specify the lookup method name in the bean definition. Copyright(c) Oded Nissan 2010
  94. 94. Method Injection Copyright(c) Oded Nissan 2010
  95. 95. Dependency Check • Sometimes we want to ensure that all properties are set on a bean. • The Spring IoC container can check for unresolved dependencies of a bean deployed into the container. • You can enable dependency checking per bean, just as with the autowiring functionality. • In XML-based configuration metadata, you specify dependency checking via the dependency-check attribute in a bean definition. Copyright(c) Oded Nissan 2010
  96. 96. Dependency Check • The dependency-check attribute can have the following values: – none – no dependency check will be done. – simple – dependency check will be done for primitive types and collections. – object – dependency checking for other beans. – all – dependency checking for all bean properties. Copyright(c) Oded Nissan 2010
  97. 97. Lifecycle Callbacks • Lifecycle callbacks allow you to interact with the spring container. • you can implement the Spring InitializingBean and DisposableBean interfaces. The container calls afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction of your beans. Copyright(c) Oded Nissan 2010
  98. 98. Lifecycle Callbacks Example using callbacks: • Copyright(c) Oded Nissan 2010
  99. 99. Lifecycle Callbacks • The problem with the former approach is that now our bean is dependent on spring specific interfaces. • An alternative is to specify the initialization and destroy callbacks in the spring configuration using the init-method and destroy-method bean attributes. Copyright(c) Oded Nissan 2010
  100. 100. Lifecycle Callbacks Using init-method: • • Using destroy-method: Copyright(c) Oded Nissan 2010
  101. 101. Lifecycle Callbacks • You can configure the Spring container to look for named initialization and destroy callback method names on every bean. • This means that you, as an application developer, can write your application classes and use an initialization callback called init() for each bean, without configuring it in the XML file. • This feature also enforces a consistent naming convention for initialization and destroy method callbacks. Copyright(c) Oded Nissan 2010
  102. 102. Lifecycle Callbacks Example of default lifecycle callbacks: • Copyright(c) Oded Nissan 2010
  103. 103. Exercise Copyright(c) Oded Nissan 2010
  104. 104. Container Shutdown Hook • In a non web environment you can also register a shutdown hook that will be called when the container is shutdown. • The shutdown hook will be called when the program’s main method exits: Copyright(c) Oded Nissan 2010
  105. 105. Injecting a Spring Context • Sometimes we will need to access the spring context from outside the spring container. • Since we don’t want to create the ApplicationContext again, we want to inject the existing ApplicationContext into our class. • To inject the spring context we write a class that implements the ApplicationContextAware interface, define it as a spring bean and provide a static method to retrieve the context. Copyright(c) Oded Nissan 2010
  106. 106. Injecting a Spring Context • Example of a helper class that the context will be injected to: Copyright(c) Oded Nissan 2010
  107. 107. Bean Definition Inheritance • Sometimes we might want to inherit the bean definition in a child bean. • A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed. • This is done by specifying the “parent” attribute in the child bean configuration. Copyright(c) Oded Nissan 2010
  108. 108. Bean Definition Inheritance • Note that bean definition inheritance does not necessarily imply class inheritance. • We can use bean definition inheritance with or without class inheritance. • We can also use class inheritance with or without bean definition inheritance. Copyright(c) Oded Nissan 2010
  109. 109. Bean Definition Inheritance • Bean definition inheritance example: Copyright(c) Oded Nissan 2010
  110. 110. Externalizing Properties • You use the PropertyPlaceholderConfigurer to externalize property values from a bean definition into another separate file in the standard Java Properties format. • Doing so enables the person deploying an application to customize environment-specific properties such as database URLs and passwords, without the complexity or risk of modifying the main XML definition file or files for the container. Copyright(c) Oded Nissan 2010
  111. 111. Externalizing Properties • This mechanism is called the PropertyPlaceholderConfigurator. To use it: – Specify placeholders for externalized properties in the bean definition: Copyright(c) Oded Nissan 2010
  112. 112. Externalizing Properties – Define the properties to be replaced and their replace values in a properties file: – Use the configuration to have the context load the properties file: Copyright(c) Oded Nissan 2010
  113. 113. Exercise Copyright(c) Oded Nissan 2010
  114. 114. Internationalization • The ApplicationContext interface extends an interface called MessageSource, to provide internationalization (i18n) functionality. • Spring also provides the interface HierarchicalMessageSource, which can resolve messages hierarchically. • The basic method to retrieve message is: – String getMessage(String code, Object[] args, String default, Locale loc) • When no message is found for the specified locale, the default message is used. • Additional flavors of the getMessage method are available. Copyright(c) Oded Nissan 2010
  115. 115. Internationalization • When an ApplicationContext is loaded, it automatically searches for a MessageSource bean defined in the context. • The bean must have the name messageSource. If such a bean is found, all calls to the preceding methods are delegated to the message source. • If no message source is found, the ApplicationContext attempts to find a parent containing a bean with the same name. If it does, it uses that bean as the MessageSource. • If the ApplicationContext cannot find any source for messages, an empty DelegatingMessageSource is instantiated in order to be able to accept calls to the methods defined above. Copyright(c) Oded Nissan 2010
  116. 116. Internationalization • Spring provides two MessageSource implementations, ResourceBundleMessageSource and StaticMessageSource. Both implement HierarchicalMessageSource. • ResourceBundleMessageSource example: Copyright(c) Oded Nissan 2010
  117. 117. Internationalization • The example assumes we have three different resource bundles called format, exceptions and windows. • Spring's various MessageResource implementations follow the same locale resolution and fallback rules as the standard JDK ResourceBundle. • The locale is appended to the file name, the suffix is “properties”. Copyright(c) Oded Nissan 2010
  118. 118. Internationalization • For example, messages for the hebrew locale will be stored in a files called • The country code can also be appended for example: • The default locale is named • We need to specify the locale so when retrieving the message. Copyright(c) Oded Nissan 2010
  119. 119. Internationalization Bundle files: • • Retrieving the messages using the ApplicationContext (Note that ApplicationContext also implements MessageSource): Copyright(c) Oded Nissan 2010
  120. 120. Summary • What did we discuss ? – What is dependency injection? – IOC container overview – Working with Spring beans – Managing dependencies – Advanced features Copyright(c) Oded Nissan 2010
  121. 121. Questions ? Copyright(c) Oded Nissan 2010
  122. 122. Resources Copyright(c) Oded Nissan 2010
  123. 123. Resources • • • • • Available Resource implementations The Resource Loader Injecting Resources ApplicationContext and Resources Resources and Wildcards Copyright(c) Oded Nissan 2010
  124. 124. Resources • Spring contains various resource implementations that support retrieving resources from difference sources. • The possible sources include the filesystem, the classpath, URLs and the ServletContext. • All resource implementations implement the Resource interface. Copyright(c) Oded Nissan 2010
  125. 125. Resources • The Resource Interface: Copyright(c) Oded Nissan 2010
  126. 126. Resources • The following resource implementations are supported by Spring: – URLResource – ClassPathResource – FileSystemResource – ServletContextResource – InputStreamResource – ByteArrayResource Copyright(c) Oded Nissan 2010
  127. 127. Resources • Resources are loaded by a ResourceLoader, there are various implementations of the ResourceLoader interface that support loading different resources. • All application contexts implement the ResourceLoader interface, and therefore all application contexts may be used to obtain Resource instances. Copyright(c) Oded Nissan 2010
  128. 128. Resources • When you call getResource() on a specific application context, and the location path specified doesn't have a specific prefix, you will get back a Resource type that is appropriate to that particular application context. For example this would return a ClassPathResource : Copyright(c) Oded Nissan 2010
  129. 129. Resources • You can also force ClassPathResource to be used, regardless of the application context type, by specifying the special classpath: prefix: • Or a url prefix or file prefix: Copyright(c) Oded Nissan 2010
  130. 130. Injecting Resources • Resources can also be injected to beans using dependency injection. When the property is of a resource type the values will be used to initialize the appropriate resource. In the following examples the appropriate resource type will be initialized: Copyright(c) Oded Nissan 2010
  131. 131. Application Contexts and Resources • The constructor of an ApplicationContext takes a path String as a parameter and uses the appropriate resource loader for the specific ApplicationContext implementation used. For example: Copyright(c) Oded Nissan 2010
  132. 132. Resources and Wildcards • Resource paths may contain the special "classpath*:" prefix and/or internal Ant-style regular expressions. • One use for this mechanism is when doing component-style application assembly. All components can 'publish' context definition fragments to a well-known location path, and all of them will be picked up by the applicationcontext using wildcards. Copyright(c) Oded Nissan 2010
  133. 133. Resources and Wildcards • Ant style regular expression examples: • In this example all resources matching the regular expressions will be loaded. Copyright(c) Oded Nissan 2010
  134. 134. Resources and Wildcards • Using the classpath*: prefix : • In this example all resources found in the classpath with the “conf/appContext.xml” path will be loaded. Copyright(c) Oded Nissan 2010
  135. 135. Exercise Copyright(c) Oded Nissan 2010
  136. 136. Summary • What did we discuss ? – Available Resource implementations – The Resource Loader – Injecting Resources – ApplicationContext and Resources – Resources and Wildcards Copyright(c) Oded Nissan 2010
  137. 137. Questions ? Copyright(c) Oded Nissan 2010
  138. 138. Spring AOP Copyright(c) Oded Nissan 2010
  139. 139. Spring AOP • • • • • What is AOP ? AOP Concepts Spring AOP options Example Summary Copyright(c) Oded Nissan 2010
  140. 140. What is AOP ? • Aspect-Oriented Programming (AOP) is an important technology, well-suited to solving many common problems. Spring offers AOP features to complement its IoC features and ensure that enterprise service code does not pollute your application objects. • Spring takes a pragmatic approach to AOP. You can use as little AOP as you want, or integrate with AspectJ to harness the power of AOP extensions to the Java language. Copyright(c) Oded Nissan 2010
  141. 141. AOP Concepts • Aspect: a modularization of a concern that cuts across multiple classes. • Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception. • Advice: action taken by an aspect at a particular join point. • Pointcut: a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut Copyright(c) Oded Nissan 2010
  142. 142. AOP Concepts • Introduction- declaring additional methods or fields on behalf of a type. • Target object- object being advised by one or more aspects. • AOP proxy- an object created by the AOP framework in order to implement the aspect contracts. • Weaving - linking aspects with other application types or objects to create an advised object. Copyright(c) Oded Nissan 2010
  143. 143. Advice Types • Before advice- Advice that executes before a join point. • After returning advice- Advice to be executed after a join point completes normally. • After throwing advice- Advice to be executed if a method exits by throwing an exception. • After (finally) advice- Advice to be executed regardless of the means by which a join point exits. • Around advice- Advice that surrounds a join point such as a method invocation. Copyright(c) Oded Nissan 2010
  144. 144. Spring AOP • Spring AOP is implemented in pure Java. There is no need for a special compilation process. • One of the central tenets of the Spring Framework is that of non-invasiveness; this is the idea that you should not be forced to introduce framework-specific classes and interfaces into your business/domain model. Copyright(c) Oded Nissan 2010
  145. 145. AOP Proxies • Spring AOP defaults to using standard J2SE dynamic proxies for AOP proxies. This enables any interface to be proxied. • Spring AOP can also use CGLIB proxies. This is necessary to proxy classes, rather than interfaces. CGLIB is used by default if a business object does not implement an interface. Copyright(c) Oded Nissan 2010
  146. 146. AOP Proxies • When using dynamic proxies, a proxy object is generated on the fly for the proxied object. The proxy object then intercepts the method calls on the real object. • The proxy can then advices on the object and also invoke the real method on the real object. Copyright(c) Oded Nissan 2010
  147. 147. AOP Proxies • Spring provides an API to programmatically apply dynamic proxies to objects. • Here we can see the “foo” method intercepted by the proxy: Copyright(c) Oded Nissan 2010
  148. 148. Spring AOP • There are currently 3 options for using Spring AOP: – @AspectJ style annotations. – Schema based AOP support – Old Spring AOP APIs (prior to version 2.0) Copyright(c) Oded Nissan 2010
  149. 149. @AspectJ Support • @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations. • Spring 2.0 interprets the same annotations as AspectJ 5, using a library supplied by AspectJ for pointcut parsing and matching. • The AOP runtime is still pure Spring AOP though, and there is no dependency on the AspectJ compiler or weaver. Copyright(c) Oded Nissan 2010
  150. 150. Schema based AOP Support • Spring also offers support for defining aspects using the new "aop" namespace tags. • The exact same pointcut expressions and advice kinds are supported as when using the @AspectJ style. • Definitions will be done in XML rather than in annotations. Copyright(c) Oded Nissan 2010
  151. 151. AspectJ@ vs. schema based AOP • XML can be used with any Java version. • XML can be changed without changing and compiling code. • AspectJ@ annotations unite the code with the configuration. • The @AspectJ style supports additional instantiation models, and richer pointcut composition. • We will discuss only schema based AOP. Copyright(c) Oded Nissan 2010
  152. 152. Using AOP • To use Spring AOP: – Write a bean with your advice methods. – Declare the bean to be an aspect. – Specify the pointcut to which the aspect will be applied in the configuration file. – Specify the advice to be applied to the pointcut in the configuration file. Copyright(c) Oded Nissan 2010
  153. 153. Spring AOP Pointcut expressions • execution - for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP • within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP) • this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type • target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type Copyright(c) Oded Nissan 2010
  154. 154. Spring AOP Pointcut expressions • args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types • @target - limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type • @args - limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given type(s) • @within - limits matching to join points within types that have the given annotation (the execution of methods declared in types with the given annotation when using Spring AOP) • @annotation - limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation Copyright(c) Oded Nissan 2010
  155. 155. AOP Pointcut Expressions • Execution of any public method. • Execution of any method in the AccountService interface. • Execution of any method in the service package. • Execution of any method in the service package or any of its subpackages Copyright(c) Oded Nissan 2010
  156. 156. AOP Pointcut Expressions • Any joinpoint within the service package. • Any join point where the proxy implements the AccountService interface. • Any join point where the target object implements the AccountService interface. • Any join point with a single parameter of type Serializable. Copyright(c) Oded Nissan 2010
  157. 157. Spring AOP Example • We want to profile a method execution by measuring the time it takes to execute the method. • We define the SimpleProfiler class as an aspect. • We apply an around advice to the getFoo method in theFooService interface. Copyright(c) Oded Nissan 2010
  158. 158. Spring AOP Example • We define a FooService interface and implement it. Copyright(c) Oded Nissan 2010
  159. 159. Spring AOP Example • We write the SimpleProfiler class which will serve as the aspect. We write the profile method as an around advice. Copyright(c) Oded Nissan 2010
  160. 160. Spring AOP Example • We use XML configuration to apply the advice of the SimpleProfiler aspect to the FooService interface. Copyright(c) Oded Nissan 2010
  161. 161. Spring AOP Example • The following is a test driver invoking the bean the aspect was applied on and the resulting output. Copyright(c) Oded Nissan 2010
  162. 162. Exercise Copyright(c) Oded Nissan 2010
  163. 163. Spring Best Practices • • • • Prefer setter based injection. Use naming conventions for beans. Try to avoid using autowiring. Carefully check the need for prototype scope beans. • Reuse bean definitions when possible. • Use AOP carefully. • Not every class is a Spring bean Copyright(c) Oded Nissan 2010
  164. 164. Summary • What did we discuss ? – What is AOP ? – AOP Concepts – Spring AOP options – Example Copyright(c) Oded Nissan 2010