Introduction to spring

164
Introduction to Spring Oded Nissan

description

 

Transcript of Introduction to spring

Page 1: Introduction to spring

Introduction to Spring

Oded Nissan

Page 2: Introduction to spring

Introduction to Spring

• Introduction• About the Lecturer• Topics• Exercises• Agenda• Questions ?

Copyright(c) Oded Nissan 2010

Page 3: Introduction to spring

Introduction to Spring

• Introduction• About the Lecturer• Topics• Exercises• Agenda• Questions ?

Copyright(c) Oded Nissan 2010

Page 4: Introduction to spring

Agenda

• Spring architecture and overview• Dependency Injection and the IOC Container• Resources• Spring AOP• Summary

Copyright(c) Oded Nissan 2010

Page 5: Introduction to spring

Spring architecture and overview

• Spring Introduction• Spring Architecture• The Spring Framework Components

Copyright(c) Oded Nissan 2010

Page 6: Introduction to spring

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

Page 7: Introduction to spring

Resources

• Available Resource implementations• The Resource Loader• Injecting Resources• ApplicationContext and Resources• Resources and Wildcards

Copyright(c) Oded Nissan 2010

Page 8: Introduction to spring

Spring AOP

• What is AOP ?• AOP Concepts• Spring AOP options• Example• Summary

Copyright(c) Oded Nissan 2010

Page 9: Introduction to spring

Spring architecture and overview

Copyright(c) Oded Nissan 2010

Page 10: Introduction to spring

Spring architecture and overview

• Spring Introduction• Spring Architecture• The Spring Framework Components

Copyright(c) Oded Nissan 2010

Page 11: Introduction to spring

Resources• http://www.springsource.org - the home of the

Spring Framework.• http://www.springhub.com – a hub for Spring

resources.• http://static.springsource.org/spring/docs/current/s

pring-framework-reference/html/ - the Spring Framework reference documentation.

• http://static.springsource.org/spring/docs/3.0.x/javadoc-api/ - Spring API docs.

• http://opensource.atlassian.com/confluence/spring/dashboard.action - Spring community wiki.

Copyright(c) Oded Nissan 2010

Page 12: Introduction to spring

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

Page 13: Introduction to spring

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

Page 14: Introduction to spring

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

Page 15: Introduction to spring

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

Page 16: Introduction to spring

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

Page 17: Introduction to spring

Spring Architecture

Copyright(c) Oded Nissan 2010

Page 18: Introduction to spring

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

Page 19: Introduction to spring

Full Spring Web application

Copyright(c) Oded Nissan 2010

Page 20: Introduction to spring

Spring as a Middle Tier

Copyright(c) Oded Nissan 2010

Page 21: Introduction to spring

Spring as a Remoting Framework

Copyright(c) Oded Nissan 2010

Page 22: Introduction to spring

Spring Framework Components

• IOC Container.• Aspect Oriented Programming Framework.• Data access abstraction.• Transaction management.• MVC web framework.• Integration

Copyright(c) Oded Nissan 2010

Page 23: Introduction to spring

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

Page 24: Introduction to spring

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

Page 25: Introduction to spring

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

Page 26: Introduction to spring

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 SQL-based 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

Page 27: Introduction to spring

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

Page 28: Introduction to spring

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

Page 29: Introduction to spring

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

Page 30: Introduction to spring

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

Page 31: Introduction to spring

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

Page 32: Introduction to spring

The MVC Pattern

Copyright(c) Oded Nissan 2010

Page 33: Introduction to spring

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

Page 34: Introduction to spring

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

Page 35: Introduction to spring

Summary

• What did we discuss ?– Spring Introduction– Spring Architecture– The Spring Framework Components

Copyright(c) Oded Nissan 2010

Page 36: Introduction to spring

Questions?

Copyright(c) Oded Nissan 2010

Page 37: Introduction to spring

Dependency Injection and the IOC Container

Copyright(c) Oded Nissan 2010

Page 38: Introduction to spring

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

Page 39: Introduction to spring

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

Page 40: Introduction to spring

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

Page 41: Introduction to spring

What is dependency injection?

•An example and discussion.

Copyright(c) Oded Nissan 2010

Page 42: Introduction to spring

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

Page 43: Introduction to spring

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

Page 44: Introduction to spring

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

Page 45: Introduction to spring

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

Page 46: Introduction to spring

IOC Container Overview

Copyright(c) Oded Nissan 2010

Page 47: Introduction to spring

IOC Container Overview

Copyright(c) Oded Nissan 2010

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.

Page 48: Introduction to spring

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

Page 49: Introduction to spring

Instantiating a Container

Copyright(c) Oded Nissan 2010

Page 50: Introduction to spring

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

Page 51: Introduction to spring

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

Page 52: Introduction to spring

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

Page 53: Introduction to spring

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

Page 54: Introduction to spring

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

Page 55: Introduction to spring

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

Page 56: Introduction to spring

Using a Factory

• Using a static factory:

Copyright(c) Oded Nissan 2010

• Using an instance factory:

Page 57: Introduction to spring

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

Page 58: Introduction to spring

Setter based Dependency injection

• Initializing a bean using XML:

Copyright(c) Oded Nissan 2010

• Retrieving the bean:

Page 59: Introduction to spring

Setter based Dependency injection

• The bean class includes the appropriate getters and setters for the properties:

Copyright(c) Oded Nissan 2010

Page 60: Introduction to spring

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

Page 61: Introduction to spring

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

Page 62: Introduction to spring

Constructor based Dependency Injection

• For example, see the constructors of SampleBean:

Copyright(c) Oded Nissan 2010

• And the XML definition:

Page 63: Introduction to spring

Constructor based Dependency Injection

• In this case we need to specify the argument type to the container to prevent ambiguity:

Copyright(c) Oded Nissan 2010

• We can also specify the argument position when the constructor has multiple arguments:

Page 64: Introduction to spring

Dependency Injection

• Spring’s dependency injection framework allows injecting the following types:– Primitive values– References to other beans– Collections

Copyright(c) Oded Nissan 2010

Page 65: Introduction to spring

Dependency Injection

• Injecting beans using method injection:

Copyright(c) Oded Nissan 2010

Page 66: Introduction to spring

Dependency Injection

• Injecting beans using constructor injection:

Copyright(c) Oded Nissan 2010

Page 67: Introduction to spring

Collections Dependency Injection

• You can use the <list>, <map> and <props> to inject collections into beans.

Copyright(c) Oded Nissan 2010

Page 68: Introduction to spring

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

Page 69: Introduction to spring

Collections Dependency Injection

• Collections Merging:

Copyright(c) Oded Nissan 2010

Page 70: Introduction to spring

Exercise

Copyright(c) Oded Nissan 2010

Page 71: Introduction to spring

Injecting Empty Values

• Spring can inject empty values using an empty string or a <null> element:

Copyright(c) Oded Nissan 2010

Page 72: Introduction to spring

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

Page 73: Introduction to spring

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

Page 74: Introduction to spring

Inner Beans

• A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean.

• An inner bean is anonymous and is always of prototype scope.

Copyright(c) Oded Nissan 2010

Page 75: Introduction to spring

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

Page 76: Introduction to spring

Depends On

• The <depends-on> tag can also specify several dependencies separated by commas.

Copyright(c) Oded Nissan 2010

Page 77: Introduction to spring

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

Page 78: Introduction to spring

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

Page 79: Introduction to spring

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

Page 80: Introduction to spring

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

Page 81: Introduction to spring

Autowiring Example

Copyright(c) Oded Nissan 2010

Page 82: Introduction to spring

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

Page 83: Introduction to spring

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

Page 84: Introduction to spring

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 top-level <beans/> element accepts one or more patterns within its default-autowire-candidates attribute.

Copyright(c) Oded Nissan 2010

Page 85: Introduction to spring

Exercise

Copyright(c) Oded Nissan 2010

Page 86: Introduction to spring

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

Page 87: Introduction to spring

Bean ScopesBean 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

Page 88: Introduction to spring

The Singleton Scope

Copyright(c) Oded Nissan 2010

Page 89: Introduction to spring

The Prototype Scope

Copyright(c) Oded Nissan 2010

Page 90: Introduction to spring

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

Page 91: Introduction to spring

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

Page 92: Introduction to spring

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

Page 93: Introduction to spring

Method Injection

• We create the singleton bean, with the method that lookups the prototype bean as abstract. With the following signature:

Copyright(c) Oded Nissan 2010

• We then specify the lookup method name in the bean definition.

Page 94: Introduction to spring

Method Injection

Copyright(c) Oded Nissan 2010

Page 95: Introduction to spring

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

Page 96: Introduction to spring

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

Page 97: Introduction to spring

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

Page 98: Introduction to spring

Lifecycle Callbacks

•Example using callbacks:

Copyright(c) Oded Nissan 2010

Page 99: Introduction to spring

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

Page 100: Introduction to spring

Lifecycle Callbacks

•Using init-method:

Copyright(c) Oded Nissan 2010

• Using destroy-method:

Page 101: Introduction to spring

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

Page 102: Introduction to spring

Lifecycle Callbacks

•Example of default lifecycle callbacks:

Copyright(c) Oded Nissan 2010

Page 103: Introduction to spring

Exercise

Copyright(c) Oded Nissan 2010

Page 104: Introduction to spring

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

Page 105: Introduction to spring

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

Page 106: Introduction to spring

Injecting a Spring Context

• Example of a helper class that the context will be injected to:

Copyright(c) Oded Nissan 2010

Page 107: Introduction to spring

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

Page 108: Introduction to spring

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

Page 109: Introduction to spring

Bean Definition Inheritance

• Bean definition inheritance example:

Copyright(c) Oded Nissan 2010

Page 110: Introduction to spring

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

Page 111: Introduction to spring

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

Page 112: Introduction to spring

Externalizing Properties

– Define the properties to be replaced and their replace values in a properties file:

Copyright(c) Oded Nissan 2010

– Use the configuration to have the context load the properties file:

Page 113: Introduction to spring

Exercise

Copyright(c) Oded Nissan 2010

Page 114: Introduction to spring

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

Page 115: Introduction to spring

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

Page 116: Introduction to spring

Internationalization

• Spring provides two MessageSource implementations, ResourceBundleMessageSource and StaticMessageSource. Both implement HierarchicalMessageSource.

• ResourceBundleMessageSource example:

Copyright(c) Oded Nissan 2010

Page 117: Introduction to spring

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

Page 118: Introduction to spring

Internationalization

• For example, messages for the hebrew locale will be stored in a files called format_he.properties.

• The country code can also be appended for example: format_he_IL.properties.

• The default locale is named format.properties.• We need to specify the locale so when

retrieving the message.

Copyright(c) Oded Nissan 2010

Page 119: Introduction to spring

Internationalization

•Bundle files:

Copyright(c) Oded Nissan 2010

• Retrieving the messages using the ApplicationContext (Note that ApplicationContext also implements MessageSource):

Page 120: Introduction to spring

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

Page 121: Introduction to spring

Questions?

Copyright(c) Oded Nissan 2010

Page 122: Introduction to spring

Resources

Copyright(c) Oded Nissan 2010

Page 123: Introduction to spring

Resources

• Available Resource implementations• The Resource Loader• Injecting Resources• ApplicationContext and Resources• Resources and Wildcards

Copyright(c) Oded Nissan 2010

Page 124: Introduction to spring

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

Page 125: Introduction to spring

Resources

• The Resource Interface:

Copyright(c) Oded Nissan 2010

Page 126: Introduction to spring

Resources

• The following resource implementations are supported by Spring:– URLResource – ClassPathResource– FileSystemResource– ServletContextResource– InputStreamResource– ByteArrayResource

Copyright(c) Oded Nissan 2010

Page 127: Introduction to spring

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

Page 128: Introduction to spring

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

Page 129: Introduction to spring

Resources

• You can also force ClassPathResource to be used, regardless of the application context type, by specifying the special classpath: prefix:

Copyright(c) Oded Nissan 2010

• Or a url prefix or file prefix:

Page 130: Introduction to spring

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

Page 131: Introduction to spring

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

Page 132: Introduction to spring

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

Page 133: Introduction to spring

Resources and Wildcards

• Ant style regular expression examples:

Copyright(c) Oded Nissan 2010

• In this example all resources matching the regular expressions will be loaded.

Page 134: Introduction to spring

Resources and Wildcards

• Using the classpath*: prefix :

Copyright(c) Oded Nissan 2010

• In this example all resources found in the classpath with the “conf/appContext.xml” path will be loaded.

Page 135: Introduction to spring

Exercise

Copyright(c) Oded Nissan 2010

Page 136: Introduction to spring

Summary

• What did we discuss ?– Available Resource implementations– The Resource Loader– Injecting Resources– ApplicationContext and Resources– Resources and Wildcards

Copyright(c) Oded Nissan 2010

Page 137: Introduction to spring

Questions?

Copyright(c) Oded Nissan 2010

Page 138: Introduction to spring

Spring AOP

Copyright(c) Oded Nissan 2010

Page 139: Introduction to spring

Spring AOP

• What is AOP ?• AOP Concepts• Spring AOP options• Example• Summary

Copyright(c) Oded Nissan 2010

Page 140: Introduction to spring

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

Page 141: Introduction to spring

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

Page 142: Introduction to spring

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

Page 143: Introduction to spring

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

Page 144: Introduction to spring

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

Page 145: Introduction to spring

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

Page 146: Introduction to spring

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

Page 147: Introduction to spring

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

Page 148: Introduction to spring

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

Page 149: Introduction to spring

@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

Page 150: Introduction to spring

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

Page 151: Introduction to spring

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

Page 152: Introduction to spring

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

Page 153: Introduction to spring

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

Page 154: Introduction to spring

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

Page 155: Introduction to spring

AOP Pointcut Expressions

• Execution of any public method.

Copyright(c) Oded Nissan 2010

• 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

Page 156: Introduction to spring

AOP Pointcut Expressions• Any joinpoint within the service package.

Copyright(c) Oded Nissan 2010

• 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.

Page 157: Introduction to spring

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

Page 158: Introduction to spring

Spring AOP Example

• We define a FooService interface and implement it.

Copyright(c) Oded Nissan 2010

Page 159: Introduction to spring

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

Page 160: Introduction to spring

Spring AOP Example

• We use XML configuration to apply the advice of the SimpleProfiler aspect to the FooService interface.

Copyright(c) Oded Nissan 2010

Page 161: Introduction to spring

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

Page 162: Introduction to spring

Exercise

Copyright(c) Oded Nissan 2010

Page 163: Introduction to spring

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

Page 164: Introduction to spring

Summary

• What did we discuss ?– What is AOP ?– AOP Concepts– Spring AOP options– Example

Copyright(c) Oded Nissan 2010