SlideShare a Scribd company logo
Spring Framework Official Spring site: http://www.springframework.org Spring Documentation: http://www.springframework.org/documentation www.intellibitz.com   [email_address]
Spring Overview www.intellibitz.com   [email_address]
Spring Background In early 2004, Martin Fowler asked the readers of his site: when talking about Inversion of Control: “the question is, what aspect of control are [they] inverting?”. Fowler then suggested renaming the principle (or at least giving it a more self-explanatory name), and started to use the term Dependency Injection. www.intellibitz.com   [email_address]
Spring Introduction The IoC component of the Spring Framework addresses the enterprise concern of taking the classes, objects, and services that are to compose an application, by providing a formalized means of composing these various disparate components into a fully working application ready for use. www.intellibitz.com   [email_address]
Spring Introduction The Spring Framework takes best practices that have been proven over the years in numerous applications and formalized as design patterns, and actually codifies these patterns as first class objects that you as an architect and developer can take away and integrate into your own application(s). www.intellibitz.com   [email_address]
Spring Package - Core The Core package provides the IoC and Dependency Injection features. The basic concept here is the BeanFactory, which provides a sophisticated implementation of the factory pattern which removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic. www.intellibitz.com   [email_address]
Spring Package - Context The Context package provides a way to access objects in a framework-style manner in a fashion somewhat reminiscent of a JNDI-registry. The context package inherits its features from the beans package and adds support for internationalization (I18N), event-propagation, resource-loading, and the transparent creation of contexts by, for example, a servlet container. www.intellibitz.com   [email_address]
Spring Package - DAO The DAO package provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs (plain old Java objects) www.intellibitz.com   [email_address]
Spring Package - ORM The ORM package provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis. 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. www.intellibitz.com   [email_address]
Spring Package - AOP Spring's AOP package provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code implementing functionality that should logically speaking be separated. www.intellibitz.com   [email_address]
Spring Package - WEB Spring's Web package provides basic web-oriented integration features, such as multipart file-upload functionality, the initialization of the IoC container using servlet listeners and a web-oriented application context. When using Spring together with WebWork or Struts, this is the package to integrate with. www.intellibitz.com   [email_address]
Spring Package - MVC Spring's MVC package provides a Model-View-Controller (MVC) implementation for web-applications. Spring's MVC framework is not just any old implementation; it provides a clean separation between domain model code and web forms, and allows you to use all the other features of the Spring Framework. www.intellibitz.com   [email_address]
Spring Web Application www.intellibitz.com   [email_address]
Spring Web Application By using Spring's declarative transaction management features  the web application is fully transactional, just as it would be when using container managed transactions as provided by Enterprise JavaBeans. All your custom business logic can be implemented using simple POJOs, managed by Spring's IoC container. www.intellibitz.com   [email_address]
Spring Web Application Additional services include support for sending email, and validation that is independent of the web layer enabling you to choose where to execute validation rules. Spring's ORM support is integrated with JPA, Hibernate, JDO and iBatis; for example, when using Hibernate, you can continue to use your existing mapping files and standard Hibernate SessionFactory configuration. www.intellibitz.com   [email_address]
Spring Middle Tier - 3 rd  Party www.intellibitz.com   [email_address]
Spring Middle Tier - 3 rd  Party The Spring Framework does not force you to use everything within it; it is not an all-or-nothing  solution.  Existing front-ends built using WebWork, Struts, Tapestry, or other UI frameworks can be integrated perfectly well with a Spring-based middle-tier, allowing you to use the transaction features that Spring offers. The only thing you need to do is wire up your business logic using an ApplicationContext and integrate your web layer using a WebApplicationContext. www.intellibitz.com   [email_address]
Spring Remoting Usage www.intellibitz.com   [email_address]
Spring Remoting Usage When you need to access existing code via web services, you can use Spring's Hessian-, Burlap-, Rmi-  or JaxRpcProxyFactory classes. Enabling remote access to existing applications suddenly is not that hard anymore. www.intellibitz.com   [email_address]
Spring EJB – Wrapping POJO's www.intellibitz.com   [email_address]
Spring EJB – Wrapping POJO's The Spring Framework also provides an access- and abstraction- layer for Enterprise JavaBeans, enabling you to reuse your existing POJOs and wrap them in Stateless Session Beans, for use in scalable, failsafe web applications that might need declarative security. www.intellibitz.com   [email_address]
JDK Support The Spring Framework continues to be totally compatible with all versions of Java since (and including) Java 1.3. This means that 1.3, 1.4, and 1.5 are supported, although some advanced functionality of the Spring Framework may not be available to you if you are (for example) committed to using Java 1.3. www.intellibitz.com   [email_address]
The IOC Container The BeanFactory  interface provides an advanced configuration mechanism capable of managing objects of any nature. The ApplicationContext  interface builds on top of the BeanFactory  (it is a sub-interface) and adds additional functionality such as easier integration with application-layer specific contexts such as the WebApplicationContext for use in web applications. www.intellibitz.com   [email_address]
The IOC Container In short, the BeanFactory provides the configuration framework and basic functionality, while the ApplicationContext adds more enterprise-centric functionality to it. The ApplicationContext is a complete superset of the BeanFactory, and any description of BeanFactory capabilities and behavior is to be considered to apply to the ApplicationContext as well. www.intellibitz.com   [email_address]
BeanFactory vs ApplicationContext Users are sometimes unsure whether a BeanFactory or an ApplicationContext is best suited for use in a particular situation. A BeanFactory  pretty much just instantiates and configures beans. An ApplicationContext also does that, and it provides the supporting infrastructure to enable lots of enterprise features such as transactions and AOP. In short, favor the use of an ApplicationContext. www.intellibitz.com   [email_address]
Container and Beans Objects that form the backbone of your application and that are managed by the Spring IoC container are referred to as beans. A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container; These beans, and the dependencies between them, are reflected in the configuration metadata used by a container. www.intellibitz.com   [email_address]
Container and Beans Why... bean? The motivation for using the name 'bean', as opposed to 'component' or 'object' is rooted in the origins of the Spring Framework itself (it arose partly as a response to the complexity of Enterprise JavaBeans). www.intellibitz.com   [email_address]
The Spring IOC Container www.intellibitz.com   [email_address]
The Spring IOC Container The  org.springframework.beans.factory.BeanFactory   is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC container interface in Spring. Its responsibilities include instantiating or sourcing application objects, configuring such objects, and assembling the dependencies between these objects. www.intellibitz.com   [email_address]
The Spring IOC Container There are a number of implementations of the BeanFactory interface that come supplied straight out-of-the-box with Spring. The most commonly used BeanFactory implementation is the XmlBeanFactory class. This implementation allows you to express the objects that compose your application, and interdependencies between such objects, in terms of XML. The XmlBeanFactory takes this XML configuration and uses it to create a fully configured system. www.intellibitz.com   [email_address]
Configuration Metadata Configuration metadata is nothing more than how you inform the Spring container as to how to “instantiate, configure, and assemble [the objects in your application]”.  This configuration metadata is typically supplied in a simple and intuitive XML format. When using XML, you write bean definitions for those beans that you want the Spring IoC container to manage, and then let the container do it's stuff. www.intellibitz.com   [email_address]
Configuration Metadata Spring configuration consists of at least one bean definition that the container must manage, but typically there will be more than one bean definition. When using XML-based configuration metadata, these beans are configured as <bean/> elements inside a top-level <beans/>  element. www.intellibitz.com   [email_address]
Configuration Metadata Typically you will have bean definitions for your service layer objects, your DAOs, presentation objects such as Struts Action, infrastructure objects such as Hibernate SessionFactory, JMS Queue references, etc.  (the possibilities are limited only by the scope and complexity of your application). (Typically one does not configure fine-grained domain objects in the container.) www.intellibitz.com   [email_address]
Configuration Metadata <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <beans xmlns=&quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot;> <bean id=&quot;...&quot; class=&quot;...&quot;> <!-- collaborators and configuration for this bean go here --> </bean> <bean id=&quot;...&quot; class=&quot;...&quot;> <!-- collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions go here... --> </beans> www.intellibitz.com   [email_address]
Container Instantiation Instantiating a Spring IoC container is easy;  Resource resource = new FileSystemResource(&quot;beans.xml&quot;); BeanFactory factory = new XmlBeanFactory(resource); ... or... ClassPathResource resource = new ClassPathResource(&quot;beans.xml&quot;); BeanFactory factory = new XmlBeanFactory(resource); ... or... ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {&quot;applicationContext.xml&quot;, &quot;applicationContext-part2.xml&quot;}); // of course, an ApplicationContext is just a BeanFactory BeanFactory factory = (BeanFactory) context; www.intellibitz.com   [email_address]
Container Instantiation The location path or paths supplied to an ApplicationContext constructor are actually resource strings that allow the container to load configuration metadata from a variety of external resources such as the local file system, from the Java CLASSPATH, etc. www.intellibitz.com   [email_address]
Composing Configuration XML It can often be useful to split up container definitions into multiple XML files. One way to then load an application context which is configured from all these XML fragments is to use the application context constructor which takes multiple Resource locations. With a bean factory, a bean definition reader can be used multiple times to read definitions from each file in turn. www.intellibitz.com   [email_address]
Composing Configuration XML An alternate approach is to use one or more occurrences of the <import/> element to load bean definitions from another file (or files). Any <import/> elements must be placed before <bean/> elements in the file doing the importing. www.intellibitz.com   [email_address]
Composing Configuration XML <beans> <import resource=&quot;services.xml&quot;/> <import resource=&quot;resources/messageSource.xml&quot;/> <import resource=&quot;/resources/themeSource.xml&quot;/> <bean id=&quot;bean1&quot; class=&quot;...&quot;/> <bean id=&quot;bean2&quot; class=&quot;...&quot;/> </beans> www.intellibitz.com   [email_address]
Spring Beans Spring IoC container manages one or more beans created using the instructions defined in the configuration metadata that has been supplied to the container (typically in the form of XML <bean/> definitions). Within the container itself, these bean definitions are represented as BeanDefinition objects, which contain (among other information) the following metadata: www.intellibitz.com   [email_address]
Spring Beans a package-qualified class name: this is normally the actual implementation class of the bean being defined.  bean behavioral configuration elements, which state how the bean should behave in the container (prototype or singleton, autowiring mode, initialization and destruction callbacks, and so forth). www.intellibitz.com   [email_address]
Spring Beans constructor arguments and property values to set in the newly created bean. An example would be the number of connections to use in a bean that manages a connection pool (either specified as a property or as a constructor argument), or the pool size limit. other beans which are needed for the bean to do its work, that is collaborators (also called dependencies). www.intellibitz.com   [email_address]
Spring Beans Besides bean definitions which contain information on how to create a specific bean, certain BeanFactory  implementations also permit the registration of existing objects that have been created outside the factory (by user code). The DefaultListableBeanFactory class supports this through the registerSingleton(..) method. www.intellibitz.com   [email_address]
Naming Beans Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases. www.intellibitz.com   [email_address]
Naming Beans Please note that you are not required to supply a name for a bean. If no name is supplied explicitly, the container will generate a (unique) name for that bean. The motivations for not supplying a name for a bean will be discussed later (one use case is inner beans). www.intellibitz.com   [email_address]
Bean Naming Conventions The convention is to use the standard Java convention for instance field names when naming beans. That is, bean names start with a lowercase letter, and are camel-cased from then on. Examples of such names would be (without quotes) 'accountManager', 'accountService', 'userDao', 'loginController', etc. www.intellibitz.com   [email_address]
Aliasing Beans It is sometimes desirable to introduce an alias for a bean which is defined elsewhere. <alias name=&quot;fromName&quot; alias=&quot;toName&quot;/> In this case, a bean in the same container which is named 'fromName', may also after the use of this alias definition, be referred to as 'toName'. www.intellibitz.com   [email_address]
Instantiating Beans A bean definition can be seen as a recipe for creating one or more actual objects. The container looks at the recipe for a named bean, and uses the configuration metadata encapsulated by that bean definition to create (or acquire) an actual object. specify the type (or class) of object that is to be instantiated using the 'class' attribute of the <bean/> element. www.intellibitz.com   [email_address]
Instantiating using Constructor Specify the bean class <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean&quot;/> <bean name=&quot;anotherExample&quot; class=&quot;examples.ExampleBeanTwo&quot;/> Spring IoC container isn't limited to just managing true JavaBeans, it is also able to manage virtually any  class you want it to manage. www.intellibitz.com   [email_address]
Instantiating using static factory method When defining a bean which is to be created using a static factory method, along with the class attribute which specifies the class containing the static factory method, another attribute named factory-method is needed to specify the name of the factory method itself. <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean2&quot; factory-method=&quot;createInstance&quot;/> www.intellibitz.com   [email_address]
Using the Container A BeanFactory is essentially nothing more than the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies. InputStream is = new FileInputStream(&quot;beans.xml&quot;); BeanFactory factory = new XmlBeanFactory(is); Using getBean(String) you can retrieve instances of your beans; www.intellibitz.com   [email_address]
The BeanFactory interface boolean containsBean(String):  Object getBean(String):  Object getBean(String, Class):  Class getType(String name):  boolean isSingleton(String):  String[] getAliases(String):  www.intellibitz.com   [email_address]
Dependencies A application will have at least a handful of objects that work together to present what the end-user sees as a coherent application. You can define a number of bean definitions that stand-alone, each to themselves, to a fully realized application where objects work (or collaborate) together to achieve some goal (usually an application that does what the end-user wants). www.intellibitz.com   [email_address]
Injecting Dependencies It becomes evident upon usage that code gets much cleaner when the DI principle is applied, and reaching a higher grade of decoupling is much easier when beans do not look up their dependencies, but are provided with them (and additionally do not even know where the dependencies are located and of what actual class they are). www.intellibitz.com   [email_address]
Setter Injection Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. www.intellibitz.com   [email_address] public class SimpleMovieLister { // the SimpleMovieLister has a dependency on the MovieFinder private MovieFinder movieFinder; // a setter method so that the Spring container can 'inject' a MovieFinder public void setMovieFinder (MovieFinder movieFinder) { this.movieFinder = movieFinder; } }
Constructor Injection Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator. Additionally, calling a static factory method can be considered almost equivalent. www.intellibitz.com   [email_address] public class SimpleMovieLister { // the SimpleMovieLister has a dependency on the MovieFinder private MovieFinder movieFinder; // a constructor so that the Spring container can 'inject' a MovieFinder public SimpleMovieLister (MovieFinder movieFinder) { this.movieFinder = movieFinder; } }
Constructor or Setter DI? Setter based DI makes objects of that class amenable to being re-configured (or re-injected) at some later time (for management via JMX MBeans is a particularly compelling use case).  Constructor-injection Supplying all of an object's dependencies means that that object is never returned to client (calling) code in a less than totally initialized state. www.intellibitz.com   [email_address]
Bean Dependency Resolution The BeanFactory is created and initialized with a configuration which describes all the beans.  Each bean has dependencies expressed in the form of properties, constructor arguments. These dependencies will be provided to the bean, when the bean is actually created. www.intellibitz.com   [email_address]
Bean Dependency Resolution Each property or constructor argument is either an actual definition of the value to set, or a reference to another bean in the container. Each property or constructor argument which is a value must be able to be converted from whatever format it was specified in, to the actual type of that property or constructor argument. By default Spring can convert a value supplied in string format to all built-in types, such as int, long, String, boolean, etc.  www.intellibitz.com   [email_address]
Setter based DI - Examples <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean&quot;> <!-- setter injection using the nested <ref/> element --> <property name=&quot;beanOne&quot;><ref bean=&quot;anotherExampleBean&quot;/></property> <!-- setter injection using the neater 'ref' attribute --> <property name=&quot;beanTwo&quot; ref=&quot;yetAnotherBean&quot;/> <property name=&quot;integerProperty&quot; value=&quot;1&quot;/> </bean> <bean id=&quot;anotherExampleBean&quot; class=&quot;examples.AnotherBean&quot;/> <bean id=&quot;yetAnotherBean&quot; class=&quot;examples.YetAnotherBean&quot;/> www.intellibitz.com   [email_address]
Setter based DI - Examples public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public void setBeanOne(AnotherBean beanOne) { this.beanOne = beanOne; } public void setBeanTwo(YetAnotherBean beanTwo) { this.beanTwo = beanTwo; } public void setIntegerProperty(int i) { this.i = i; }  } www.intellibitz.com   [email_address]
Constructor based DI - Examples <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean&quot;> <!-- constructor injection using the nested <ref/> element --> <constructor-arg><ref bean=&quot;anotherExampleBean&quot;/></constructor-arg> <!-- constructor injection using the neater 'ref' attribute --> <constructor-arg ref=&quot;yetAnotherBean&quot;/> <constructor-arg type=&quot;int&quot; value=&quot;1&quot;/> </bean> <bean id=&quot;anotherExampleBean&quot; class=&quot;examples.AnotherBean&quot;/> <bean id=&quot;yetAnotherBean&quot; class=&quot;examples.YetAnotherBean&quot;/> www.intellibitz.com   [email_address]
Constructor based DI - Examples public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public ExampleBean( AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) { this.beanOne = anotherBean; this.beanTwo = yetAnotherBean; this.i = i; } } www.intellibitz.com   [email_address]
Bean Properties detailed Straight values (primitives, Strings, etc.) The <value/> element specifies a property or constructor argument as a human-readable string representation. As mentioned previously, JavaBeans PropertyEditors are used to convert these string values from a String to the actual type of the property or argument. www.intellibitz.com   [email_address]
Bean Properties detailed <bean id=&quot;myDataSource&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot; destroy-method=&quot;close&quot;> <!-- results in a setDriverClassName(String) call --> <property name=&quot;driverClassName&quot;> <value>com.mysql.jdbc.Driver</value> </property> <property name=&quot;url&quot;> <value>jdbc:mysql://localhost:3306/mydb</value> </property> <property name=&quot;username&quot;> <value>root</value> </property> <property name=&quot;password&quot;> <value>masterkaoli</value> </property> </bean> www.intellibitz.com   [email_address] <bean id=&quot;myDataSource&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot; destroy-method=&quot;close&quot;> <!-- results in a setDriverClassName(String) call --> <property name=&quot;driverClassName&quot; value=&quot;com.mysql.jdbc.Driver&quot;/> <property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/mydb&quot;/> <property name=&quot;username&quot; value=&quot;root&quot;/> <property name=&quot;password&quot; value=&quot;masterkaoli&quot;/> </bean>
The idref element The idref element is simply an error-proof way to pass the id of another bean in the container (to a <constructor-arg/> or <property/>  element). using the idref tag allows the container to validate at deployment time that the referenced, named bean actually exists. www.intellibitz.com   [email_address]
The idref element Additionally, if the bean being referred to is in the same XML unit, and the bean name is the bean id, the 'local'  attribute may be used, which allows the XML parser itself to validate the bean id even earlier, at XML document parse time. <property name=&quot;targetName&quot;> <!-- a bean with an id of 'theTargetBean' must exist, otherwise an XML exception will be thrown --> <idref local=&quot;theTargetBean&quot;/> </property> www.intellibitz.com   [email_address]
References to Colloborators The  ref  element is used to set the value of the specified property to be a reference to another bean managed by the container (a collaborator). the referred-to bean is a dependency of the bean who's property is being set, and will be initialized on demand (if it is a singleton bean it may have already been initialized by the container) before the property is set.  www.intellibitz.com   [email_address]
The ref element using the  bean   attribute of the  <ref/>  tag will allow creating a reference to any bean in the same container (whether or not in the same XML file), or parent container.  The value of the 'bean' attribute may be the same as either the 'id' attribute of the target bean, or one of the values in the 'name' attribute of the target bean. <ref bean=&quot;someBean&quot;/> www.intellibitz.com   [email_address]
The ref element using the  local  attribute leverages the ability of the XML parser to validate XML id references within the same file. The value of the local attribute must be the same as the id attribute of the target bean.  The XML parser will issue an error if no matching element is found in the same file. As such, using the local variant is the best choice if the target bean is in the same XML file. <ref local=&quot;someBean&quot;/> www.intellibitz.com   [email_address]
The ref element Specifying the target bean by using the ' parent '  attribute allows a reference to be created to a bean which is in a parent container of the current container. The main use of this is when you have a hierarchy of containers and you want to wrap an existing bean in a parent container with some sort of proxy which will have the same name as the parent bean. www.intellibitz.com   [email_address]
The ref element <!-- in the parent context --> <bean id=&quot;accountService&quot; class=&quot;com.foo.SimpleAccountService&quot;> <!-- insert dependencies as required as here --> </bean> <!-- in the child (descendant) context --> <bean id=&quot;accountService&quot;  <-- notice that the name of this bean is the same as the name of the 'parent' bean--> class=&quot;org.springframework.aop.framework.ProxyFactoryBean&quot;> <property name=&quot;target&quot;> <ref parent=&quot;accountService&quot;/>  <-- notice how we refer to the parent bean--> </property> <!-- insert other configuration and dependencies as required as here --> </bean> www.intellibitz.com   [email_address]
Inner Beans A  <bean/>  element inside the  <property/>  or  <constructor-arg/>   elements is used to define a so-called inner bean. An inner bean definition does not need to have any id or name defined, and it is best not to even specify any id or name value because the id or name value simply will be ignored by the container. <bean id=&quot;outer&quot; class=&quot;...&quot;> <!-- instead of using a reference to a target bean, simply define the target bean inline --> <property name=&quot;target&quot;> <bean class=&quot;com.mycompany.Person&quot;> <!-- this is the inner bean --> <property name=&quot;name&quot; value=&quot;Fiona Apple&quot;/> </bean> </property> </bean> Note  that in the specific case of inner beans, the 'scope' flag and any 'id' or 'name' attribute are effectively ignored. Inner beans are always anonymous and they are always scoped as prototypes. Please also note that it is not possible to inject inner beans into collaborating beans other than the enclosing bean. www.intellibitz.com   [email_address]
Collections The  <list/> ,  <set/> ,  <map/> , and  <props/>  elements allow properties and arguments of the Java type List, Set, Map, and Properties, respectively, to be defined and set. Note that the value of a map key or value, or a set value, can also again be any of the following elements: bean | ref | idref | list | set | map | props | value | null www.intellibitz.com   [email_address]
Collections <bean id=&quot;moreComplexObject&quot; class=&quot;example.ComplexObject&quot;> <!-- results in a setAdminEmails(java.util.Properties) call --> <property name=&quot;adminEmails&quot;> <props> <prop key=&quot;administrator&quot;> administrator@somecompany.org</prop> <prop key=&quot;support&quot;> support@somecompany.org</prop> <prop key=&quot;development&quot;> development@somecompany.org</prop> </props>  </property> <!-- results in a setSomeList(java.util.List) call --> <property name=&quot;someList&quot;> <list> <value>a list element followed by a reference</value> <ref bean=&quot;myDataSource&quot; /> </list>  </property> www.intellibitz.com   [email_address] <!--results in a setSomeMap(java.util.Map) call --> <property name=&quot;someMap&quot;> <map> <entry>  <key> <value>yup an entry</value></key> <value>just some string</value></entry> <entry>  <key> <value>yup a ref</value> </key> <ref bean=&quot;myDataSource&quot; /> </entry> </map> </property> <!-- results in a setSomeSet(java.util.Set) call --> <property name=&quot;someSet&quot;> <set> <value>just some string</value> <ref bean=&quot;myDataSource&quot; /> </set>  </property> </bean>
Collection Merging This allows 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;  that is to say the child values will be the result from merging of elements of the parent and child collections, with the child's elements overriding values specified in the parent collection. www.intellibitz.com   [email_address]
Collection Merging <beans> <bean id=&quot;parent&quot; abstract=&quot;true&quot; class=&quot;example.ComplexObject&quot;> <property name=&quot;adminEmails&quot;> <props> <prop key=&quot;administrator&quot;>administrator@somecompany.com</prop> <prop key=&quot;support&quot;>support@somecompany.com</prop> </props> </property> </bean> <bean id=&quot;child&quot; parent=&quot;parent&quot;> <property name=&quot;adminEmails&quot;> <!-- the merge is specified on the *child* collection definition --> <props merge=&quot;true&quot;> <prop key=&quot;sales&quot;>sales@somecompany.com</prop> <prop key=&quot;support&quot;>support@somecompany.co.uk</prop> </props> </property> </bean> <beans> www.intellibitz.com   [email_address]
Collection Merging Strongly-typed Collection If you are using Spring to dependency inject a strongly-typed Collection into a bean, you can take advantage of Spring's type-conversion support such that the elements of your strongly-typed Collection instances will be converted to the appropriate type prior to being added to the Collection. www.intellibitz.com   [email_address]
Collection Merging Strongly-typed Collection public class Foo { private Map<String, Float> accounts; public void setAccounts(Map<String, Float> accounts) { this.accounts = accounts; } } <beans> <bean id=&quot;foo&quot; class=&quot;x.y.Foo&quot;> <property name=&quot;accounts&quot;> <map> <entry key=&quot;one&quot; value=&quot;9.99&quot;/> <entry key=&quot;two&quot; value=&quot;2.75&quot;/> </map> </property> </bean> </beans> www.intellibitz.com   [email_address]
Nulls The <null/> element is used to handle null values. Spring treats empty arguments for properties and the like as empty Strings. The following XML-based configuration metadata snippet results in the email property being set to the empty String value (&quot;&quot;) <bean class=&quot;ExampleBean&quot;> <property name=&quot;email&quot;><value/></property> </bean> www.intellibitz.com   [email_address] This is equivalent to the following Java code:  exampleBean.setEmail(&quot;&quot;).  The special <null> element may be used to indicate a null value. For example: <bean class=&quot;ExampleBean&quot;> <property name=&quot;email&quot;><null/></property> </bean> The above configuration is equivalent to the following Java code:  exampleBean.setEmail(null).
Configuration metadata shortcuts <property name=&quot;myProperty&quot;> <value>hello</value></property> <constructor-arg> <value>hello</value></constructor-arg> <entry key=&quot;myKey&quot;> <value>hello</value></entry> <property name=&quot;myProperty&quot;> <ref bean=&quot;myBean&quot;></property> <constructor-arg> <ref bean=&quot;myBean&quot;></constructor-arg> <entry> <key>  <ref bean=&quot;myKeyBean&quot; /> </key>  <ref bean=&quot;myValueBean&quot; /> </entry> www.intellibitz.com   [email_address] <property name=&quot;myProperty&quot; value=&quot;hello&quot;/> <constructor-arg value=&quot;hello&quot;/> <entry key=&quot;myKey&quot; value=&quot;hello&quot;/> <property name=&quot;myProperty&quot; ref=&quot;myBean&quot;/> <constructor-arg ref=&quot;myBean&quot;/> <entry key-ref=&quot;myKeyBean&quot; value-ref=&quot;myValueBean&quot;/>
Compound property names Compound or nested property names are perfectly legal when setting bean properties, as long as all components of the path except the final property name are not null.  <bean id=&quot;foo&quot; class=&quot;foo.Bar&quot;> <property name=&quot;fred.bob.sammy&quot; value=&quot;123&quot; /> </bean> fred  property of  foo , and the  bob  property of  fred  must both be non-null after the bean is constructed, or a  NullPointerException  be thrown. www.intellibitz.com   [email_address]
Using depends-on depends-on' attribute may be used to explicitly force one or more beans to be initialized before the bean using this element is initialized. <bean id=&quot;beanOne&quot; class=&quot;ExampleBean&quot; depends-on=&quot;manager,accountDao&quot;> <property name=&quot;manager&quot; ref=&quot;manager&quot; /> </bean> <bean id=&quot;manager&quot; class=&quot;ManagerBean&quot; /> <bean id=&quot;accountDao&quot; class=&quot;x.y.jdbc.JdbcAccountDao&quot; /> Note  The 'depends-on' attribute and property is used not only to specify an initialization time dependency, but also to specify the corresponding destroy time dependency (in the case of singleton beans only). Dependant beans that are defined in the 'depends-on' attribute will be destroyed first prior to the relevant bean itself being destroyed. This thus allows you to control shutdown order too. www.intellibitz.com   [email_address]
Lazily-instantiated Beans If you do not want a singleton bean to be pre-instantiated when using an  ApplicationContext , you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first requested. www.intellibitz.com   [email_address]
Lazily-instantiated Beans <bean id=&quot;lazy&quot; class=&quot;com.foo.ExpensiveToCreateBean&quot;  lazy-init=&quot;true&quot;/> <bean name=&quot;not.lazy&quot; class=&quot;com.foo.AnotherBean&quot;/> the bean named 'lazy' will not be eagerly pre-instantiated when the ApplicationContext is starting up, whereas the 'not.lazy' bean will be eagerly pre-instantiated. www.intellibitz.com   [email_address] It is also possible to control lazy-initialization at the container level by using the 'default-lazy-init' attribute on the <beans/>  element; for example: <beans default-lazy-init=&quot;true&quot;> <!-- no beans will be pre-instantiated... --> </beans>
Bean Scopes singleton Scopes a single bean definition to a single object instance per Spring IoC container. prototype Scopes a single bean definition to any number of object instances. www.intellibitz.com   [email_address]
Bean Scopes - Singleton www.intellibitz.com   [email_address]
Bean Scopes - Prototype www.intellibitz.com   [email_address]
Bean Scopes request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition.  session Scopes a single bean definition to the lifecycle of a HTTP Session.  www.intellibitz.com   [email_address]
Bean Scopes global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context.  request, session, and global session are for use only in web-based applications (and can be used irrespective of which particular web application framework you are using, if indeed any). www.intellibitz.com   [email_address]
Initial web configuration If you are using a Servlet 2.4+ web container, then you need only add the following ContextListener to the XML declarations in your web application's 'web.xml' file. <web-app> ... <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> ... </web-app> www.intellibitz.com   [email_address]
The Request Scope <bean id=&quot;loginAction&quot; class=&quot;com.foo.LoginAction&quot; scope=&quot;request&quot;/> the Spring container creates a new  LoginAction  bean using the ' loginAction ' bean definition for each and every HTTP request.  You can change the state of the instance that is created, safe in the knowledge that other requests that are also using instances created off the back of the same 'loginAction' bean definition will not be seeing these changes since they are particular to an individual request. After request processing, the bean scoped to the request will be discarded. www.intellibitz.com   [email_address]
The Session Scope <bean id=&quot;userPreferences&quot; class=&quot;com.foo.UserPreferences&quot; scope=&quot;session&quot;/> the container creates a new  UserPreferences  bean using the ' userPreferences ' definition for the lifetime of a single HTTP Session.  You can change the instance, safe in the knowledge that other HTTP Session instances that are also using instances created of the same 'userPreferences' bean definition will not be seeing these changes since they are particular to an individual HTTP Session. When HTTP Session is discarded, the bean that is scoped to that particular HTTP Session will also be discarded. www.intellibitz.com   [email_address]
The Global Session Scope <bean id=&quot;userPreferences&quot; class=&quot;com.foo.UserPreferences&quot; scope=&quot;globalSession&quot;/> The global session scope is similar to the standard HTTP Session scope, and used in the context of portlet-based web applications.  The portlet specification defines the notion of a global Session that is shared amongst all of the various portlets that make up a single portlet web application. Beans defined at the global session scope are scoped (or bound) to the lifetime of the global portlet Session. Please note that if you are writing a standard Servlet-based web application and you define one or more beans as having global session scope, the standard HTTP Session scope will be used, and no error will be raised. www.intellibitz.com   [email_address]
Scoped Beans as Dependencies to inject a (for example) HTTP request scoped bean into another bean, you will need to inject an AOP proxy in place of the scoped bean. That is, you need to inject a proxy object that exposes the same public interface as the scoped object, but that is smart enough to be able to retrieve the real, target object from the relevant scope and delegate method calls onto the real object. www.intellibitz.com   [email_address]
Scoped Beans as Dependencies <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <beans xmlns=&quot; http://www.springframework.org/schema/beans &quot;  xmlns:xsi=&quot; http://www.w3.org/2001/XMLSchema-instance &quot;  xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;  xsi:schemaLocation=&quot; http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans-2.0.xsd   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd&quot;> <!-- a HTTP Session-scoped bean exposed as a proxy --> <bean id=&quot;userPreferences&quot; class=&quot;com.foo.UserPreferences&quot; scope=&quot;session&quot;> <!-- this next element effects the proxying of the surrounding bean --> <aop:scoped-proxy/> </bean> <!-- a singleton-scoped bean injected with a proxy to the above bean --> <bean id=&quot;userService&quot; class=&quot;com.foo.SimpleUserService&quot;> <!-- a reference to the proxied 'userPreferences' bean --> <property name=&quot;userPreferences&quot; ref=&quot;userPreferences&quot;/> </bean> </beans> www.intellibitz.com   [email_address]
Customizing Bean nature Lifecycle interfaces The Spring Framework provides several marker interfaces to change the behavior of your bean in the container; they include InitializingBean and DisposableBean. Implementing these interfaces will result in the container calling afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction. www.intellibitz.com   [email_address]
Initialization Callbacks Implementing the  org.springframework.beans.factory.InitializingBean   interface allows a bean to perform initialization work after all necessary properties on the bean are set by the container. The InitializingBean interface specifies exactly one method: void afterPropertiesSet() throws Exception; www.intellibitz.com   [email_address]
Initialization Callbacks Generally, the use of the InitializingBean interface can be avoided (and is discouraged since it unnecessarily couples the code to Spring). A bean definition provides support for a generic initialization method to be specified. In the case of XML-based configuration metadata, this is done using the 'init-method' attribute. www.intellibitz.com   [email_address]
Initialization Callbacks <bean id=&quot;exampleInitBean&quot; class=&quot;examples.ExampleBean&quot; init-method=&quot;init&quot;/> public class ExampleBean { public void init() { // do some initialization work } } Is exactly the same as... <bean id=&quot;exampleInitBean&quot; class=&quot;examples.AnotherExampleBean&quot;/> public class AnotherExampleBean implements InitializingBean { public void afterPropertiesSet() { // do some initialization work } } ... but does not couple the code to Spring. www.intellibitz.com   [email_address]
Destruction Callbacks Implementing the  org.springframework.beans.factory.DisposableBean   interface allows a bean to get a callback when the container containing it is destroyed. The DisposableBean interface specifies one method: void destroy() throws Exception; www.intellibitz.com   [email_address]
Destruction Callbacks <bean id=&quot;exampleInitBean&quot; class=&quot;examples.ExampleBean&quot; destroy-method=&quot;cleanup&quot;/> public class ExampleBean { public void cleanup() { // do some destruction work (like releasing pooled connections) } } Is exactly the same as... <bean id=&quot;exampleInitBean&quot; class=&quot;examples.AnotherExampleBean&quot;/> public class AnotherExampleBean implements DisposableBean { public void destroy() { // do some destruction work (like releasing pooled connections) } } ... but does not couple the code to Spring. www.intellibitz.com   [email_address]
Default initialization & destroy methods The Spring container can now be configured to 'look'  for named initialization and destroy callback method names on every bean.  www.intellibitz.com   [email_address] public class DefaultBlogService implements BlogService { private BlogDao blogDao; public void setBlogDao(BlogDao blogDao) { this.blogDao = blogDao; } // this is (unsurprisingly) the initialization callback method public void init() { if (this.blogDao == null) { throw new IllegalStateException(&quot;The [blogDao] property must be set.&quot;); } } } <beans default-init-method=&quot;init&quot;> <bean id=&quot;blogService&quot; class=&quot;com.foo.DefaultBlogService&quot;> <property name=&quot;blogDao&quot; ref=&quot;blogDao&quot; /> </bean> </beans>
BeanFactoryAware A class which implements the  org.springframework.beans.factory.BeanFactoryAware   interface is provided with a reference to the  BeanFactory  that created it, when it is created by that  BeanFactory . public interface BeanFactoryAware { void setBeanFactory(BeanFactory beanFactory) throws BeansException; } This allows beans to manipulate the BeanFactory that created them programmatically, through the BeanFactory interface, or by casting the reference to a known subclass of this which exposes additional functionality.  www.intellibitz.com   [email_address]
BeanNameAware If a bean implements the  org.springframework.beans.factory.BeanNameAware   interface and is deployed in a  BeanFactory , the  BeanFactory  will call the bean through this interface to inform the bean of the id it was deployed under.  The callback is invoked after population of bean properties but before initialization callback like  afterPropertiesSet  or a custom init-method. www.intellibitz.com   [email_address]
Bean definition inheritance A bean definition potentially contains a large amount of configuration information, including container specific information and constructor arguments and property values. A child bean definition is a bean definition that inherits configuration data from a parent definition. It is then able to override some values, or add others, as needed. Using parent and child bean definitions this way, is a form of templating. www.intellibitz.com   [email_address]
Bean definition inheritance a child bean definition is indicated simply by using the 'parent'  attribute, specifying the parent bean as the value of this attribute. <bean id=&quot;inheritedTestBean&quot; abstract=&quot;true&quot; class=&quot;org.springframework.beans.TestBean&quot;> <property name=&quot;name&quot; value=&quot;parent&quot;/> <property name=&quot;age&quot; value=&quot;1&quot;/> </bean> <bean id=&quot;inheritsWithDifferentClass&quot; class=&quot;org.springframework.beans.DerivedTestBean&quot; parent=&quot;inheritedTestBean&quot; init-method=&quot;initialize&quot;> <property name=&quot;name&quot; value=&quot;override&quot;/> <!-- the age property value of 1 will be inherited from  parent --> </bean> www.intellibitz.com   [email_address]
Bean definition inheritance <bean id=&quot;inheritedTestBeanWithoutClass&quot; abstract=&quot;true&quot;> <property name=&quot;name&quot; value=&quot;parent&quot;/> <property name=&quot;age&quot; value=&quot;1&quot;/> </bean> <bean id=&quot;inheritsWithClass&quot; class=&quot;org.springframework.beans.DerivedTestBean&quot; parent=&quot;inheritedTestBeanWithoutClass&quot; init-method=&quot;initialize&quot;> <property name=&quot;name&quot; value=&quot;override&quot;/> <!-- age will inherit the value of 1 from the parent bean definition--> </bean> www.intellibitz.com   [email_address] The parent bean cannot get instantiated on its own since it is incomplete, and it is also explicitly marked as abstract. it is usable only as a pure template bean definition that will serve as a parent definition for child definitions. Trying to use such an abstract parent bean on its own (by referring to it as a ref property, or doing an explicit getBean() call with the parent bean id), will result in an error.
BeanPostProcessor This interface defines a number of callback methods that you can implement in order to provide your own (or override the containers default) instantiation logic, dependency-resolution logic, and so forth.  to do some custom logic after the Spring container has finished instantiating, configuring and otherwise initializing a bean, you can plug in one or more  BeanPostProcessor  implementations. www.intellibitz.com   [email_address]
BeanPostProcessor BeanPostProcessors operate on bean (or object) instances.  If you want to change the actual bean definition, then you rather need to use a  BeanFactoryPostProcessor . Also, BeanPostProcessors are scoped per-container. If you define a  BeanPostProcessor  in one container, it will only do its stuff on the beans in that container.  www.intellibitz.com   [email_address]
PropertyPlaceholderConfigurer The  PropertyPlaceholderConfigurer  is used to externalize property values from a  BeanFactory  definition, into another separate file in the standard Java Properties format. This is useful to allow the person deploying an application to customize enviroment-specific properties, without the complexity or risk of modifying the main XML definition file or files for the container. www.intellibitz.com   [email_address]
PropertyPlaceholderConfigurer <bean class=&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;> <property name=&quot;locations&quot;> <value>classpath:com/foo/jdbc.properties</value> </property> </bean> <bean id=&quot;dataSource&quot; destroy-method=&quot;close&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot;> <property name=&quot;driverClassName&quot; value=&quot;${jdbc.driverClassName}&quot;/> <property name=&quot;url&quot; value=&quot;${jdbc.url}&quot;/> <property name=&quot;username&quot; value=&quot;${jdbc.username}&quot;/> <property name=&quot;password&quot; value=&quot;${jdbc.password}&quot;/> </bean> The actual values come from another file in the standard Java Properties format: jdbc.driverClassName=org.hsqldb.jdbcDriver jdbc.url=jdbc:hsqldb:hsql://production:9002 jdbc.username=sa jdbc.password=root www.intellibitz.com   [email_address]
The ApplicationContext Deriving from the BeanFactory interface, it provides all the functionality of BeanFactory. also provides the following functionality: MessageSource, providing access to messages in i18n-style Access to resources, such as URLs and files Event propagation to beans implementing the ApplicationListener interface Loading of multiple (hierarchical) contexts, allowing each to be focused on one particular layer, for example the web layer of an application www.intellibitz.com   [email_address]
Internationalization using MessageSources The ApplicationContext interface extends an interface called MessageSource, and therefore provides messaging (i18n or internationalization) functionality. Together with the HierarchicalMessageSource, capable of resolving hierarchical messages, these are the basic interfaces Spring provides to do message resolution.  www.intellibitz.com   [email_address]
Internationalization using MessageSources When an ApplicationContext gets loaded, it automatically searches for a MessageSource bean defined in the context. The bean has to have the name messageSource.  <beans> <bean id=&quot;messageSource&quot; class=&quot;org.springframework.context.support.ResourceBundleMessageSource&quot;> <property name=&quot;basenames&quot;> <list> <value>format</value> <value>exceptions</value> <value>windows</value> </list> </property> </bean> </beans> www.intellibitz.com   [email_address]
Events Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. If a bean which implements the ApplicationListener interface is deployed into the context, every time an ApplicationEvent  gets published to the ApplicationContext, that bean will be notified. Essentially, this is the standard Observer  design pattern. www.intellibitz.com   [email_address]
Events ContextRefreshedEvent Published when the ApplicationContext is initialized or refreshed. Initialized here means that all beans are loaded, singletons are pre-instantiated and the ApplicationContext is ready for use. www.intellibitz.com   [email_address]
Events ContextClosedEvent Published when the ApplicationContext is closed, using the close() method on the ApplicationContext. Closed here means that singleton beans (only!) are destroyed. www.intellibitz.com   [email_address]
Events RequestHandledEvent A web-specific event telling all beans that a HTTP request has been serviced (this will be published after the request has been finished). Note that this event is only applicable for web applications using Spring's DispatcherServlet. www.intellibitz.com   [email_address]
ApplicationContext for web You can register an ApplicationContext using the ContextLoaderListener as follows: <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- or use the ContextLoaderServlet instead of the above listener <servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> --> www.intellibitz.com   [email_address]
ApplicationContext for web The listener inspects the  contextConfigLocation  parameter. If it doesn't exist, it'll use  /WEB-INF/applicationContext.xml  as a default. When it does exist, it'll separate the String using predefined delimiters (comma, semi-colon and whitespace) and use the values as locations where application contexts will be searched for. The  ContextLoaderServlet  can be used instead of the  ContextLoaderListener .  www.intellibitz.com   [email_address]
Spring Summary The Spring IOC Container The BeanFactory and ApplicationContext Bean Scopes and Bean definition inheritance Customizing Beans with Callbacks BeanPostProcessors and Internationalization Events Configuring ApplicationContext for the web www.intellibitz.com   [email_address]
Resources Official Spring site: http://www.springframework.org Spring Documentation: http://www.springframework.org/documentation Spring Forum: http://forum.springframework.org www.intellibitz.com   [email_address]
About IntelliBitz Technologies http://training.intellibitz.com http://groups.google.com/group/etoe http://sted.sourceforge.net 168, Medavakkam Main Road, Madipakkam Chennai, 600091, India. +91 44 2247 5106 [email_address] www.intellibitz.com   [email_address]
Spring says Good Bye! Thank You! www.intellibitz.com   [email_address]

More Related Content

What's hot (20)

PDF
Spring Boot
Jaydeep Kale
 
PPT
Spring Boot in Action
Alex Movila
 
PDF
Introduction to Spring Boot!
Jakub Kubrynski
 
PDF
Building RESTful applications using Spring MVC
IndicThreads
 
PDF
Spring Framework
NexThoughts Technologies
 
PPTX
Spring boot
sdeeg
 
ODP
Xke spring boot
sourabh aggarwal
 
PPTX
Introduction to Spring Boot
Purbarun Chakrabarti
 
PPTX
Spring Boot Tutorial
Naphachara Rattanawilai
 
PPT
Java EE Introduction
ejlp12
 
PPTX
Spring boot - an introduction
Jonathan Holloway
 
PPTX
Spring boot
Gyanendra Yadav
 
PDF
Spring Security
Sumit Gole
 
PPTX
Spring framework in depth
Vinay Kumar
 
PDF
Spring Security
Knoldus Inc.
 
PPTX
Spring Boot
Jiayun Zhou
 
PPTX
Introduction to Spring Framework
Serhat Can
 
PDF
Spring Boot
HongSeong Jeon
 
PPT
Spring mvc
Lhouceine OUHAMZA
 
PDF
Spring MVC Framework
Hùng Nguyễn Huy
 
Spring Boot
Jaydeep Kale
 
Spring Boot in Action
Alex Movila
 
Introduction to Spring Boot!
Jakub Kubrynski
 
Building RESTful applications using Spring MVC
IndicThreads
 
Spring Framework
NexThoughts Technologies
 
Spring boot
sdeeg
 
Xke spring boot
sourabh aggarwal
 
Introduction to Spring Boot
Purbarun Chakrabarti
 
Spring Boot Tutorial
Naphachara Rattanawilai
 
Java EE Introduction
ejlp12
 
Spring boot - an introduction
Jonathan Holloway
 
Spring boot
Gyanendra Yadav
 
Spring Security
Sumit Gole
 
Spring framework in depth
Vinay Kumar
 
Spring Security
Knoldus Inc.
 
Spring Boot
Jiayun Zhou
 
Introduction to Spring Framework
Serhat Can
 
Spring Boot
HongSeong Jeon
 
Spring mvc
Lhouceine OUHAMZA
 
Spring MVC Framework
Hùng Nguyễn Huy
 

Viewers also liked (7)

PDF
조금 더 좋은 개발자가 된다는 것( 부제: 컨퍼런스의 발표자가 된다는 것 )
Arawn Park
 
PDF
실전! 스프링과 함께하는 환경변수 관리 변천사 발표자료
수홍 이
 
PDF
Spring framework 4.x
Arawn Park
 
PDF
spring.io를 통해 배우는 spring 개발사례
Daehwan Lee
 
PPTX
Maven의 이해
Sung Jae Park
 
PPTX
Spring 웹 프로젝트 시작하기
jiseob kim
 
PPT
sungmin slide
sungminlee
 
조금 더 좋은 개발자가 된다는 것( 부제: 컨퍼런스의 발표자가 된다는 것 )
Arawn Park
 
실전! 스프링과 함께하는 환경변수 관리 변천사 발표자료
수홍 이
 
Spring framework 4.x
Arawn Park
 
spring.io를 통해 배우는 spring 개발사례
Daehwan Lee
 
Maven의 이해
Sung Jae Park
 
Spring 웹 프로젝트 시작하기
jiseob kim
 
sungmin slide
sungminlee
 
Ad

Similar to Spring User Guide (20)

PPTX
Spring Framework Rohit
Rohit Prabhakar
 
PPT
Hybernat and structs, spring classes in mumbai
Vibrant Technologies & Computers
 
PDF
Java spring framework
Rajiv Gupta
 
ODP
Spring Mvc,Java, Spring
ifnu bima
 
PPTX
Skillwise-Spring framework 1
Skillwise Group
 
PDF
Spring 2
Aruvi Thottlan
 
PPT
Screenshot from 2024-05-28 16-46-45 (30 files merged).ppt
imjdabhinawpandey
 
PPTX
Introduction to Spring
Sujit Kumar
 
PPT
Spring - a framework written by developers
MarcioSoaresPereira1
 
PDF
An introduction to the Spring Framework
weili_at_slideshare
 
PPTX
Spring framework
Rajkumar Singh
 
PDF
Spring in Action - Sixth Edition (MEAP V04) Craig Walls
elonaolzakmx
 
PPTX
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
PPTX
Spring 1 day program
Mohit Kanwar
 
PPTX
Spring (1)
Aneega
 
PPTX
Introduction to Spring Framework
Dineesha Suraweera
 
PDF
Toms introtospring mvc
Guo Albert
 
PPT
Spring introduction
Manav Prasad
 
PPT
Spring ppt
Mumbai Academisc
 
PDF
Spring Start Here Learn What You Need And Learn It Well 1st Edition Laurentiu...
wktamhyv6089
 
Spring Framework Rohit
Rohit Prabhakar
 
Hybernat and structs, spring classes in mumbai
Vibrant Technologies & Computers
 
Java spring framework
Rajiv Gupta
 
Spring Mvc,Java, Spring
ifnu bima
 
Skillwise-Spring framework 1
Skillwise Group
 
Spring 2
Aruvi Thottlan
 
Screenshot from 2024-05-28 16-46-45 (30 files merged).ppt
imjdabhinawpandey
 
Introduction to Spring
Sujit Kumar
 
Spring - a framework written by developers
MarcioSoaresPereira1
 
An introduction to the Spring Framework
weili_at_slideshare
 
Spring framework
Rajkumar Singh
 
Spring in Action - Sixth Edition (MEAP V04) Craig Walls
elonaolzakmx
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Arjun Thakur
 
Spring 1 day program
Mohit Kanwar
 
Spring (1)
Aneega
 
Introduction to Spring Framework
Dineesha Suraweera
 
Toms introtospring mvc
Guo Albert
 
Spring introduction
Manav Prasad
 
Spring ppt
Mumbai Academisc
 
Spring Start Here Learn What You Need And Learn It Well 1st Edition Laurentiu...
wktamhyv6089
 
Ad

More from Muthuselvam RS (7)

PDF
UpsilonPiEpsilon-UniversityOfBridgeport-May1997
Muthuselvam RS
 
ODP
Gears User Guide
Muthuselvam RS
 
ODP
Ant User Guide
Muthuselvam RS
 
ODP
Subversion User Guide
Muthuselvam RS
 
ODP
CProgrammingTutorial
Muthuselvam RS
 
ODP
PHP Web Programming
Muthuselvam RS
 
ODP
Hibernate Developer Reference
Muthuselvam RS
 
UpsilonPiEpsilon-UniversityOfBridgeport-May1997
Muthuselvam RS
 
Gears User Guide
Muthuselvam RS
 
Ant User Guide
Muthuselvam RS
 
Subversion User Guide
Muthuselvam RS
 
CProgrammingTutorial
Muthuselvam RS
 
PHP Web Programming
Muthuselvam RS
 
Hibernate Developer Reference
Muthuselvam RS
 

Recently uploaded (20)

PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Digital Circuits, important subject in CS
contactparinay1
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 

Spring User Guide

  • 1. Spring Framework Official Spring site: http://www.springframework.org Spring Documentation: http://www.springframework.org/documentation www.intellibitz.com [email_address]
  • 3. Spring Background In early 2004, Martin Fowler asked the readers of his site: when talking about Inversion of Control: “the question is, what aspect of control are [they] inverting?”. Fowler then suggested renaming the principle (or at least giving it a more self-explanatory name), and started to use the term Dependency Injection. www.intellibitz.com [email_address]
  • 4. Spring Introduction The IoC component of the Spring Framework addresses the enterprise concern of taking the classes, objects, and services that are to compose an application, by providing a formalized means of composing these various disparate components into a fully working application ready for use. www.intellibitz.com [email_address]
  • 5. Spring Introduction The Spring Framework takes best practices that have been proven over the years in numerous applications and formalized as design patterns, and actually codifies these patterns as first class objects that you as an architect and developer can take away and integrate into your own application(s). www.intellibitz.com [email_address]
  • 6. Spring Package - Core The Core package provides the IoC and Dependency Injection features. The basic concept here is the BeanFactory, which provides a sophisticated implementation of the factory pattern which removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic. www.intellibitz.com [email_address]
  • 7. Spring Package - Context The Context package provides a way to access objects in a framework-style manner in a fashion somewhat reminiscent of a JNDI-registry. The context package inherits its features from the beans package and adds support for internationalization (I18N), event-propagation, resource-loading, and the transparent creation of contexts by, for example, a servlet container. www.intellibitz.com [email_address]
  • 8. Spring Package - DAO The DAO package provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs (plain old Java objects) www.intellibitz.com [email_address]
  • 9. Spring Package - ORM The ORM package provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis. 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. www.intellibitz.com [email_address]
  • 10. Spring Package - AOP Spring's AOP package provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code implementing functionality that should logically speaking be separated. www.intellibitz.com [email_address]
  • 11. Spring Package - WEB Spring's Web package provides basic web-oriented integration features, such as multipart file-upload functionality, the initialization of the IoC container using servlet listeners and a web-oriented application context. When using Spring together with WebWork or Struts, this is the package to integrate with. www.intellibitz.com [email_address]
  • 12. Spring Package - MVC Spring's MVC package provides a Model-View-Controller (MVC) implementation for web-applications. Spring's MVC framework is not just any old implementation; it provides a clean separation between domain model code and web forms, and allows you to use all the other features of the Spring Framework. www.intellibitz.com [email_address]
  • 13. Spring Web Application www.intellibitz.com [email_address]
  • 14. Spring Web Application By using Spring's declarative transaction management features the web application is fully transactional, just as it would be when using container managed transactions as provided by Enterprise JavaBeans. All your custom business logic can be implemented using simple POJOs, managed by Spring's IoC container. www.intellibitz.com [email_address]
  • 15. Spring Web Application Additional services include support for sending email, and validation that is independent of the web layer enabling you to choose where to execute validation rules. Spring's ORM support is integrated with JPA, Hibernate, JDO and iBatis; for example, when using Hibernate, you can continue to use your existing mapping files and standard Hibernate SessionFactory configuration. www.intellibitz.com [email_address]
  • 16. Spring Middle Tier - 3 rd Party www.intellibitz.com [email_address]
  • 17. Spring Middle Tier - 3 rd Party The Spring Framework does not force you to use everything within it; it is not an all-or-nothing solution. Existing front-ends built using WebWork, Struts, Tapestry, or other UI frameworks can be integrated perfectly well with a Spring-based middle-tier, allowing you to use the transaction features that Spring offers. The only thing you need to do is wire up your business logic using an ApplicationContext and integrate your web layer using a WebApplicationContext. www.intellibitz.com [email_address]
  • 18. Spring Remoting Usage www.intellibitz.com [email_address]
  • 19. Spring Remoting Usage When you need to access existing code via web services, you can use Spring's Hessian-, Burlap-, Rmi- or JaxRpcProxyFactory classes. Enabling remote access to existing applications suddenly is not that hard anymore. www.intellibitz.com [email_address]
  • 20. Spring EJB – Wrapping POJO's www.intellibitz.com [email_address]
  • 21. Spring EJB – Wrapping POJO's The Spring Framework also provides an access- and abstraction- layer for Enterprise JavaBeans, enabling you to reuse your existing POJOs and wrap them in Stateless Session Beans, for use in scalable, failsafe web applications that might need declarative security. www.intellibitz.com [email_address]
  • 22. JDK Support The Spring Framework continues to be totally compatible with all versions of Java since (and including) Java 1.3. This means that 1.3, 1.4, and 1.5 are supported, although some advanced functionality of the Spring Framework may not be available to you if you are (for example) committed to using Java 1.3. www.intellibitz.com [email_address]
  • 23. The IOC Container The BeanFactory interface provides an advanced configuration mechanism capable of managing objects of any nature. The ApplicationContext interface builds on top of the BeanFactory (it is a sub-interface) and adds additional functionality such as easier integration with application-layer specific contexts such as the WebApplicationContext for use in web applications. www.intellibitz.com [email_address]
  • 24. The IOC Container In short, the BeanFactory provides the configuration framework and basic functionality, while the ApplicationContext adds more enterprise-centric functionality to it. The ApplicationContext is a complete superset of the BeanFactory, and any description of BeanFactory capabilities and behavior is to be considered to apply to the ApplicationContext as well. www.intellibitz.com [email_address]
  • 25. BeanFactory vs ApplicationContext Users are sometimes unsure whether a BeanFactory or an ApplicationContext is best suited for use in a particular situation. A BeanFactory pretty much just instantiates and configures beans. An ApplicationContext also does that, and it provides the supporting infrastructure to enable lots of enterprise features such as transactions and AOP. In short, favor the use of an ApplicationContext. www.intellibitz.com [email_address]
  • 26. Container and Beans Objects that form the backbone of your application and that are managed by the Spring IoC container are referred to as beans. A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container; These beans, and the dependencies between them, are reflected in the configuration metadata used by a container. www.intellibitz.com [email_address]
  • 27. Container and Beans Why... bean? The motivation for using the name 'bean', as opposed to 'component' or 'object' is rooted in the origins of the Spring Framework itself (it arose partly as a response to the complexity of Enterprise JavaBeans). www.intellibitz.com [email_address]
  • 28. The Spring IOC Container www.intellibitz.com [email_address]
  • 29. The Spring IOC Container The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC container interface in Spring. Its responsibilities include instantiating or sourcing application objects, configuring such objects, and assembling the dependencies between these objects. www.intellibitz.com [email_address]
  • 30. The Spring IOC Container There are a number of implementations of the BeanFactory interface that come supplied straight out-of-the-box with Spring. The most commonly used BeanFactory implementation is the XmlBeanFactory class. This implementation allows you to express the objects that compose your application, and interdependencies between such objects, in terms of XML. The XmlBeanFactory takes this XML configuration and uses it to create a fully configured system. www.intellibitz.com [email_address]
  • 31. Configuration Metadata Configuration metadata is nothing more than how you inform the Spring container as to how to “instantiate, configure, and assemble [the objects in your application]”. This configuration metadata is typically supplied in a simple and intuitive XML format. When using XML, you write bean definitions for those beans that you want the Spring IoC container to manage, and then let the container do it's stuff. www.intellibitz.com [email_address]
  • 32. Configuration Metadata Spring configuration consists of at least one bean definition that the container must manage, but typically there will be more than one bean definition. When using XML-based configuration metadata, these beans are configured as <bean/> elements inside a top-level <beans/> element. www.intellibitz.com [email_address]
  • 33. Configuration Metadata Typically you will have bean definitions for your service layer objects, your DAOs, presentation objects such as Struts Action, infrastructure objects such as Hibernate SessionFactory, JMS Queue references, etc. (the possibilities are limited only by the scope and complexity of your application). (Typically one does not configure fine-grained domain objects in the container.) www.intellibitz.com [email_address]
  • 34. Configuration Metadata <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <beans xmlns=&quot;http://www.springframework.org/schema/beans&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd&quot;> <bean id=&quot;...&quot; class=&quot;...&quot;> <!-- collaborators and configuration for this bean go here --> </bean> <bean id=&quot;...&quot; class=&quot;...&quot;> <!-- collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions go here... --> </beans> www.intellibitz.com [email_address]
  • 35. Container Instantiation Instantiating a Spring IoC container is easy; Resource resource = new FileSystemResource(&quot;beans.xml&quot;); BeanFactory factory = new XmlBeanFactory(resource); ... or... ClassPathResource resource = new ClassPathResource(&quot;beans.xml&quot;); BeanFactory factory = new XmlBeanFactory(resource); ... or... ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {&quot;applicationContext.xml&quot;, &quot;applicationContext-part2.xml&quot;}); // of course, an ApplicationContext is just a BeanFactory BeanFactory factory = (BeanFactory) context; www.intellibitz.com [email_address]
  • 36. Container Instantiation The location path or paths supplied to an ApplicationContext constructor are actually resource strings that allow the container to load configuration metadata from a variety of external resources such as the local file system, from the Java CLASSPATH, etc. www.intellibitz.com [email_address]
  • 37. Composing Configuration XML It can often be useful to split up container definitions into multiple XML files. One way to then load an application context which is configured from all these XML fragments is to use the application context constructor which takes multiple Resource locations. With a bean factory, a bean definition reader can be used multiple times to read definitions from each file in turn. www.intellibitz.com [email_address]
  • 38. Composing Configuration XML An alternate approach is to use one or more occurrences of the <import/> element to load bean definitions from another file (or files). Any <import/> elements must be placed before <bean/> elements in the file doing the importing. www.intellibitz.com [email_address]
  • 39. Composing Configuration XML <beans> <import resource=&quot;services.xml&quot;/> <import resource=&quot;resources/messageSource.xml&quot;/> <import resource=&quot;/resources/themeSource.xml&quot;/> <bean id=&quot;bean1&quot; class=&quot;...&quot;/> <bean id=&quot;bean2&quot; class=&quot;...&quot;/> </beans> www.intellibitz.com [email_address]
  • 40. Spring Beans Spring IoC container manages one or more beans created using the instructions defined in the configuration metadata that has been supplied to the container (typically in the form of XML <bean/> definitions). Within the container itself, these bean definitions are represented as BeanDefinition objects, which contain (among other information) the following metadata: www.intellibitz.com [email_address]
  • 41. Spring Beans a package-qualified class name: this is normally the actual implementation class of the bean being defined. bean behavioral configuration elements, which state how the bean should behave in the container (prototype or singleton, autowiring mode, initialization and destruction callbacks, and so forth). www.intellibitz.com [email_address]
  • 42. Spring Beans constructor arguments and property values to set in the newly created bean. An example would be the number of connections to use in a bean that manages a connection pool (either specified as a property or as a constructor argument), or the pool size limit. other beans which are needed for the bean to do its work, that is collaborators (also called dependencies). www.intellibitz.com [email_address]
  • 43. Spring Beans Besides bean definitions which contain information on how to create a specific bean, certain BeanFactory implementations also permit the registration of existing objects that have been created outside the factory (by user code). The DefaultListableBeanFactory class supports this through the registerSingleton(..) method. www.intellibitz.com [email_address]
  • 44. Naming Beans Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases. www.intellibitz.com [email_address]
  • 45. Naming Beans Please note that you are not required to supply a name for a bean. If no name is supplied explicitly, the container will generate a (unique) name for that bean. The motivations for not supplying a name for a bean will be discussed later (one use case is inner beans). www.intellibitz.com [email_address]
  • 46. Bean Naming Conventions The convention is to use the standard Java convention for instance field names when naming beans. That is, bean names start with a lowercase letter, and are camel-cased from then on. Examples of such names would be (without quotes) 'accountManager', 'accountService', 'userDao', 'loginController', etc. www.intellibitz.com [email_address]
  • 47. Aliasing Beans It is sometimes desirable to introduce an alias for a bean which is defined elsewhere. <alias name=&quot;fromName&quot; alias=&quot;toName&quot;/> In this case, a bean in the same container which is named 'fromName', may also after the use of this alias definition, be referred to as 'toName'. www.intellibitz.com [email_address]
  • 48. Instantiating Beans A bean definition can be seen as a recipe for creating one or more actual objects. The container looks at the recipe for a named bean, and uses the configuration metadata encapsulated by that bean definition to create (or acquire) an actual object. specify the type (or class) of object that is to be instantiated using the 'class' attribute of the <bean/> element. www.intellibitz.com [email_address]
  • 49. Instantiating using Constructor Specify the bean class <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean&quot;/> <bean name=&quot;anotherExample&quot; class=&quot;examples.ExampleBeanTwo&quot;/> Spring IoC container isn't limited to just managing true JavaBeans, it is also able to manage virtually any class you want it to manage. www.intellibitz.com [email_address]
  • 50. Instantiating using static factory method When defining a bean which is to be created using a static factory method, along with the class attribute which specifies the class containing the static factory method, another attribute named factory-method is needed to specify the name of the factory method itself. <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean2&quot; factory-method=&quot;createInstance&quot;/> www.intellibitz.com [email_address]
  • 51. Using the Container A BeanFactory is essentially nothing more than the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies. InputStream is = new FileInputStream(&quot;beans.xml&quot;); BeanFactory factory = new XmlBeanFactory(is); Using getBean(String) you can retrieve instances of your beans; www.intellibitz.com [email_address]
  • 52. The BeanFactory interface boolean containsBean(String): Object getBean(String): Object getBean(String, Class): Class getType(String name): boolean isSingleton(String): String[] getAliases(String): www.intellibitz.com [email_address]
  • 53. Dependencies A application will have at least a handful of objects that work together to present what the end-user sees as a coherent application. You can define a number of bean definitions that stand-alone, each to themselves, to a fully realized application where objects work (or collaborate) together to achieve some goal (usually an application that does what the end-user wants). www.intellibitz.com [email_address]
  • 54. Injecting Dependencies It becomes evident upon usage that code gets much cleaner when the DI principle is applied, and reaching a higher grade of decoupling is much easier when beans do not look up their dependencies, but are provided with them (and additionally do not even know where the dependencies are located and of what actual class they are). www.intellibitz.com [email_address]
  • 55. Setter Injection Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. www.intellibitz.com [email_address] public class SimpleMovieLister { // the SimpleMovieLister has a dependency on the MovieFinder private MovieFinder movieFinder; // a setter method so that the Spring container can 'inject' a MovieFinder public void setMovieFinder (MovieFinder movieFinder) { this.movieFinder = movieFinder; } }
  • 56. Constructor Injection Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator. Additionally, calling a static factory method can be considered almost equivalent. www.intellibitz.com [email_address] public class SimpleMovieLister { // the SimpleMovieLister has a dependency on the MovieFinder private MovieFinder movieFinder; // a constructor so that the Spring container can 'inject' a MovieFinder public SimpleMovieLister (MovieFinder movieFinder) { this.movieFinder = movieFinder; } }
  • 57. Constructor or Setter DI? Setter based DI makes objects of that class amenable to being re-configured (or re-injected) at some later time (for management via JMX MBeans is a particularly compelling use case). Constructor-injection Supplying all of an object's dependencies means that that object is never returned to client (calling) code in a less than totally initialized state. www.intellibitz.com [email_address]
  • 58. Bean Dependency Resolution The BeanFactory is created and initialized with a configuration which describes all the beans. Each bean has dependencies expressed in the form of properties, constructor arguments. These dependencies will be provided to the bean, when the bean is actually created. www.intellibitz.com [email_address]
  • 59. Bean Dependency Resolution Each property or constructor argument is either an actual definition of the value to set, or a reference to another bean in the container. Each property or constructor argument which is a value must be able to be converted from whatever format it was specified in, to the actual type of that property or constructor argument. By default Spring can convert a value supplied in string format to all built-in types, such as int, long, String, boolean, etc. www.intellibitz.com [email_address]
  • 60. Setter based DI - Examples <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean&quot;> <!-- setter injection using the nested <ref/> element --> <property name=&quot;beanOne&quot;><ref bean=&quot;anotherExampleBean&quot;/></property> <!-- setter injection using the neater 'ref' attribute --> <property name=&quot;beanTwo&quot; ref=&quot;yetAnotherBean&quot;/> <property name=&quot;integerProperty&quot; value=&quot;1&quot;/> </bean> <bean id=&quot;anotherExampleBean&quot; class=&quot;examples.AnotherBean&quot;/> <bean id=&quot;yetAnotherBean&quot; class=&quot;examples.YetAnotherBean&quot;/> www.intellibitz.com [email_address]
  • 61. Setter based DI - Examples public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public void setBeanOne(AnotherBean beanOne) { this.beanOne = beanOne; } public void setBeanTwo(YetAnotherBean beanTwo) { this.beanTwo = beanTwo; } public void setIntegerProperty(int i) { this.i = i; } } www.intellibitz.com [email_address]
  • 62. Constructor based DI - Examples <bean id=&quot;exampleBean&quot; class=&quot;examples.ExampleBean&quot;> <!-- constructor injection using the nested <ref/> element --> <constructor-arg><ref bean=&quot;anotherExampleBean&quot;/></constructor-arg> <!-- constructor injection using the neater 'ref' attribute --> <constructor-arg ref=&quot;yetAnotherBean&quot;/> <constructor-arg type=&quot;int&quot; value=&quot;1&quot;/> </bean> <bean id=&quot;anotherExampleBean&quot; class=&quot;examples.AnotherBean&quot;/> <bean id=&quot;yetAnotherBean&quot; class=&quot;examples.YetAnotherBean&quot;/> www.intellibitz.com [email_address]
  • 63. Constructor based DI - Examples public class ExampleBean { private AnotherBean beanOne; private YetAnotherBean beanTwo; private int i; public ExampleBean( AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) { this.beanOne = anotherBean; this.beanTwo = yetAnotherBean; this.i = i; } } www.intellibitz.com [email_address]
  • 64. Bean Properties detailed Straight values (primitives, Strings, etc.) The <value/> element specifies a property or constructor argument as a human-readable string representation. As mentioned previously, JavaBeans PropertyEditors are used to convert these string values from a String to the actual type of the property or argument. www.intellibitz.com [email_address]
  • 65. Bean Properties detailed <bean id=&quot;myDataSource&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot; destroy-method=&quot;close&quot;> <!-- results in a setDriverClassName(String) call --> <property name=&quot;driverClassName&quot;> <value>com.mysql.jdbc.Driver</value> </property> <property name=&quot;url&quot;> <value>jdbc:mysql://localhost:3306/mydb</value> </property> <property name=&quot;username&quot;> <value>root</value> </property> <property name=&quot;password&quot;> <value>masterkaoli</value> </property> </bean> www.intellibitz.com [email_address] <bean id=&quot;myDataSource&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot; destroy-method=&quot;close&quot;> <!-- results in a setDriverClassName(String) call --> <property name=&quot;driverClassName&quot; value=&quot;com.mysql.jdbc.Driver&quot;/> <property name=&quot;url&quot; value=&quot;jdbc:mysql://localhost:3306/mydb&quot;/> <property name=&quot;username&quot; value=&quot;root&quot;/> <property name=&quot;password&quot; value=&quot;masterkaoli&quot;/> </bean>
  • 66. The idref element The idref element is simply an error-proof way to pass the id of another bean in the container (to a <constructor-arg/> or <property/> element). using the idref tag allows the container to validate at deployment time that the referenced, named bean actually exists. www.intellibitz.com [email_address]
  • 67. The idref element Additionally, if the bean being referred to is in the same XML unit, and the bean name is the bean id, the 'local' attribute may be used, which allows the XML parser itself to validate the bean id even earlier, at XML document parse time. <property name=&quot;targetName&quot;> <!-- a bean with an id of 'theTargetBean' must exist, otherwise an XML exception will be thrown --> <idref local=&quot;theTargetBean&quot;/> </property> www.intellibitz.com [email_address]
  • 68. References to Colloborators The ref element is used to set the value of the specified property to be a reference to another bean managed by the container (a collaborator). the referred-to bean is a dependency of the bean who's property is being set, and will be initialized on demand (if it is a singleton bean it may have already been initialized by the container) before the property is set. www.intellibitz.com [email_address]
  • 69. The ref element using the bean attribute of the <ref/> tag will allow creating a reference to any bean in the same container (whether or not in the same XML file), or parent container. The value of the 'bean' attribute may be the same as either the 'id' attribute of the target bean, or one of the values in the 'name' attribute of the target bean. <ref bean=&quot;someBean&quot;/> www.intellibitz.com [email_address]
  • 70. The ref element using the local attribute leverages the ability of the XML parser to validate XML id references within the same file. The value of the local attribute must be the same as the id attribute of the target bean. The XML parser will issue an error if no matching element is found in the same file. As such, using the local variant is the best choice if the target bean is in the same XML file. <ref local=&quot;someBean&quot;/> www.intellibitz.com [email_address]
  • 71. The ref element Specifying the target bean by using the ' parent ' attribute allows a reference to be created to a bean which is in a parent container of the current container. The main use of this is when you have a hierarchy of containers and you want to wrap an existing bean in a parent container with some sort of proxy which will have the same name as the parent bean. www.intellibitz.com [email_address]
  • 72. The ref element <!-- in the parent context --> <bean id=&quot;accountService&quot; class=&quot;com.foo.SimpleAccountService&quot;> <!-- insert dependencies as required as here --> </bean> <!-- in the child (descendant) context --> <bean id=&quot;accountService&quot; <-- notice that the name of this bean is the same as the name of the 'parent' bean--> class=&quot;org.springframework.aop.framework.ProxyFactoryBean&quot;> <property name=&quot;target&quot;> <ref parent=&quot;accountService&quot;/> <-- notice how we refer to the parent bean--> </property> <!-- insert other configuration and dependencies as required as here --> </bean> www.intellibitz.com [email_address]
  • 73. Inner Beans A <bean/> element inside the <property/> or <constructor-arg/> elements is used to define a so-called inner bean. An inner bean definition does not need to have any id or name defined, and it is best not to even specify any id or name value because the id or name value simply will be ignored by the container. <bean id=&quot;outer&quot; class=&quot;...&quot;> <!-- instead of using a reference to a target bean, simply define the target bean inline --> <property name=&quot;target&quot;> <bean class=&quot;com.mycompany.Person&quot;> <!-- this is the inner bean --> <property name=&quot;name&quot; value=&quot;Fiona Apple&quot;/> </bean> </property> </bean> Note that in the specific case of inner beans, the 'scope' flag and any 'id' or 'name' attribute are effectively ignored. Inner beans are always anonymous and they are always scoped as prototypes. Please also note that it is not possible to inject inner beans into collaborating beans other than the enclosing bean. www.intellibitz.com [email_address]
  • 74. Collections The <list/> , <set/> , <map/> , and <props/> elements allow properties and arguments of the Java type List, Set, Map, and Properties, respectively, to be defined and set. Note that the value of a map key or value, or a set value, can also again be any of the following elements: bean | ref | idref | list | set | map | props | value | null www.intellibitz.com [email_address]
  • 75. Collections <bean id=&quot;moreComplexObject&quot; class=&quot;example.ComplexObject&quot;> <!-- results in a setAdminEmails(java.util.Properties) call --> <property name=&quot;adminEmails&quot;> <props> <prop key=&quot;administrator&quot;> [email protected]</prop> <prop key=&quot;support&quot;> [email protected]</prop> <prop key=&quot;development&quot;> [email protected]</prop> </props> </property> <!-- results in a setSomeList(java.util.List) call --> <property name=&quot;someList&quot;> <list> <value>a list element followed by a reference</value> <ref bean=&quot;myDataSource&quot; /> </list> </property> www.intellibitz.com [email_address] <!--results in a setSomeMap(java.util.Map) call --> <property name=&quot;someMap&quot;> <map> <entry> <key> <value>yup an entry</value></key> <value>just some string</value></entry> <entry> <key> <value>yup a ref</value> </key> <ref bean=&quot;myDataSource&quot; /> </entry> </map> </property> <!-- results in a setSomeSet(java.util.Set) call --> <property name=&quot;someSet&quot;> <set> <value>just some string</value> <ref bean=&quot;myDataSource&quot; /> </set> </property> </bean>
  • 76. Collection Merging This allows 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; that is to say the child values will be the result from merging of elements of the parent and child collections, with the child's elements overriding values specified in the parent collection. www.intellibitz.com [email_address]
  • 77. Collection Merging <beans> <bean id=&quot;parent&quot; abstract=&quot;true&quot; class=&quot;example.ComplexObject&quot;> <property name=&quot;adminEmails&quot;> <props> <prop key=&quot;administrator&quot;>[email protected]</prop> <prop key=&quot;support&quot;>[email protected]</prop> </props> </property> </bean> <bean id=&quot;child&quot; parent=&quot;parent&quot;> <property name=&quot;adminEmails&quot;> <!-- the merge is specified on the *child* collection definition --> <props merge=&quot;true&quot;> <prop key=&quot;sales&quot;>[email protected]</prop> <prop key=&quot;support&quot;>[email protected]</prop> </props> </property> </bean> <beans> www.intellibitz.com [email_address]
  • 78. Collection Merging Strongly-typed Collection If you are using Spring to dependency inject a strongly-typed Collection into a bean, you can take advantage of Spring's type-conversion support such that the elements of your strongly-typed Collection instances will be converted to the appropriate type prior to being added to the Collection. www.intellibitz.com [email_address]
  • 79. Collection Merging Strongly-typed Collection public class Foo { private Map<String, Float> accounts; public void setAccounts(Map<String, Float> accounts) { this.accounts = accounts; } } <beans> <bean id=&quot;foo&quot; class=&quot;x.y.Foo&quot;> <property name=&quot;accounts&quot;> <map> <entry key=&quot;one&quot; value=&quot;9.99&quot;/> <entry key=&quot;two&quot; value=&quot;2.75&quot;/> </map> </property> </bean> </beans> www.intellibitz.com [email_address]
  • 80. Nulls The <null/> element is used to handle null values. Spring treats empty arguments for properties and the like as empty Strings. The following XML-based configuration metadata snippet results in the email property being set to the empty String value (&quot;&quot;) <bean class=&quot;ExampleBean&quot;> <property name=&quot;email&quot;><value/></property> </bean> www.intellibitz.com [email_address] This is equivalent to the following Java code: exampleBean.setEmail(&quot;&quot;). The special <null> element may be used to indicate a null value. For example: <bean class=&quot;ExampleBean&quot;> <property name=&quot;email&quot;><null/></property> </bean> The above configuration is equivalent to the following Java code: exampleBean.setEmail(null).
  • 81. Configuration metadata shortcuts <property name=&quot;myProperty&quot;> <value>hello</value></property> <constructor-arg> <value>hello</value></constructor-arg> <entry key=&quot;myKey&quot;> <value>hello</value></entry> <property name=&quot;myProperty&quot;> <ref bean=&quot;myBean&quot;></property> <constructor-arg> <ref bean=&quot;myBean&quot;></constructor-arg> <entry> <key> <ref bean=&quot;myKeyBean&quot; /> </key> <ref bean=&quot;myValueBean&quot; /> </entry> www.intellibitz.com [email_address] <property name=&quot;myProperty&quot; value=&quot;hello&quot;/> <constructor-arg value=&quot;hello&quot;/> <entry key=&quot;myKey&quot; value=&quot;hello&quot;/> <property name=&quot;myProperty&quot; ref=&quot;myBean&quot;/> <constructor-arg ref=&quot;myBean&quot;/> <entry key-ref=&quot;myKeyBean&quot; value-ref=&quot;myValueBean&quot;/>
  • 82. Compound property names Compound or nested property names are perfectly legal when setting bean properties, as long as all components of the path except the final property name are not null. <bean id=&quot;foo&quot; class=&quot;foo.Bar&quot;> <property name=&quot;fred.bob.sammy&quot; value=&quot;123&quot; /> </bean> fred property of foo , and the bob property of fred must both be non-null after the bean is constructed, or a NullPointerException be thrown. www.intellibitz.com [email_address]
  • 83. Using depends-on depends-on' attribute may be used to explicitly force one or more beans to be initialized before the bean using this element is initialized. <bean id=&quot;beanOne&quot; class=&quot;ExampleBean&quot; depends-on=&quot;manager,accountDao&quot;> <property name=&quot;manager&quot; ref=&quot;manager&quot; /> </bean> <bean id=&quot;manager&quot; class=&quot;ManagerBean&quot; /> <bean id=&quot;accountDao&quot; class=&quot;x.y.jdbc.JdbcAccountDao&quot; /> Note The 'depends-on' attribute and property is used not only to specify an initialization time dependency, but also to specify the corresponding destroy time dependency (in the case of singleton beans only). Dependant beans that are defined in the 'depends-on' attribute will be destroyed first prior to the relevant bean itself being destroyed. This thus allows you to control shutdown order too. www.intellibitz.com [email_address]
  • 84. Lazily-instantiated Beans If you do not want a singleton bean to be pre-instantiated when using an ApplicationContext , you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first requested. www.intellibitz.com [email_address]
  • 85. Lazily-instantiated Beans <bean id=&quot;lazy&quot; class=&quot;com.foo.ExpensiveToCreateBean&quot; lazy-init=&quot;true&quot;/> <bean name=&quot;not.lazy&quot; class=&quot;com.foo.AnotherBean&quot;/> the bean named 'lazy' will not be eagerly pre-instantiated when the ApplicationContext is starting up, whereas the 'not.lazy' bean will be eagerly pre-instantiated. www.intellibitz.com [email_address] It is also possible to control lazy-initialization at the container level by using the 'default-lazy-init' attribute on the <beans/> element; for example: <beans default-lazy-init=&quot;true&quot;> <!-- no beans will be pre-instantiated... --> </beans>
  • 86. Bean Scopes singleton Scopes a single bean definition to a single object instance per Spring IoC container. prototype Scopes a single bean definition to any number of object instances. www.intellibitz.com [email_address]
  • 87. Bean Scopes - Singleton www.intellibitz.com [email_address]
  • 88. Bean Scopes - Prototype www.intellibitz.com [email_address]
  • 89. Bean Scopes request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. session Scopes a single bean definition to the lifecycle of a HTTP Session. www.intellibitz.com [email_address]
  • 90. Bean Scopes global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. request, session, and global session are for use only in web-based applications (and can be used irrespective of which particular web application framework you are using, if indeed any). www.intellibitz.com [email_address]
  • 91. Initial web configuration If you are using a Servlet 2.4+ web container, then you need only add the following ContextListener to the XML declarations in your web application's 'web.xml' file. <web-app> ... <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> ... </web-app> www.intellibitz.com [email_address]
  • 92. The Request Scope <bean id=&quot;loginAction&quot; class=&quot;com.foo.LoginAction&quot; scope=&quot;request&quot;/> the Spring container creates a new LoginAction bean using the ' loginAction ' bean definition for each and every HTTP request. You can change the state of the instance that is created, safe in the knowledge that other requests that are also using instances created off the back of the same 'loginAction' bean definition will not be seeing these changes since they are particular to an individual request. After request processing, the bean scoped to the request will be discarded. www.intellibitz.com [email_address]
  • 93. The Session Scope <bean id=&quot;userPreferences&quot; class=&quot;com.foo.UserPreferences&quot; scope=&quot;session&quot;/> the container creates a new UserPreferences bean using the ' userPreferences ' definition for the lifetime of a single HTTP Session. You can change the instance, safe in the knowledge that other HTTP Session instances that are also using instances created of the same 'userPreferences' bean definition will not be seeing these changes since they are particular to an individual HTTP Session. When HTTP Session is discarded, the bean that is scoped to that particular HTTP Session will also be discarded. www.intellibitz.com [email_address]
  • 94. The Global Session Scope <bean id=&quot;userPreferences&quot; class=&quot;com.foo.UserPreferences&quot; scope=&quot;globalSession&quot;/> The global session scope is similar to the standard HTTP Session scope, and used in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared amongst all of the various portlets that make up a single portlet web application. Beans defined at the global session scope are scoped (or bound) to the lifetime of the global portlet Session. Please note that if you are writing a standard Servlet-based web application and you define one or more beans as having global session scope, the standard HTTP Session scope will be used, and no error will be raised. www.intellibitz.com [email_address]
  • 95. Scoped Beans as Dependencies to inject a (for example) HTTP request scoped bean into another bean, you will need to inject an AOP proxy in place of the scoped bean. That is, you need to inject a proxy object that exposes the same public interface as the scoped object, but that is smart enough to be able to retrieve the real, target object from the relevant scope and delegate method calls onto the real object. www.intellibitz.com [email_address]
  • 96. Scoped Beans as Dependencies <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <beans xmlns=&quot; http://www.springframework.org/schema/beans &quot; xmlns:xsi=&quot; http://www.w3.org/2001/XMLSchema-instance &quot; xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot; xsi:schemaLocation=&quot; http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd&quot;> <!-- a HTTP Session-scoped bean exposed as a proxy --> <bean id=&quot;userPreferences&quot; class=&quot;com.foo.UserPreferences&quot; scope=&quot;session&quot;> <!-- this next element effects the proxying of the surrounding bean --> <aop:scoped-proxy/> </bean> <!-- a singleton-scoped bean injected with a proxy to the above bean --> <bean id=&quot;userService&quot; class=&quot;com.foo.SimpleUserService&quot;> <!-- a reference to the proxied 'userPreferences' bean --> <property name=&quot;userPreferences&quot; ref=&quot;userPreferences&quot;/> </bean> </beans> www.intellibitz.com [email_address]
  • 97. Customizing Bean nature Lifecycle interfaces The Spring Framework provides several marker interfaces to change the behavior of your bean in the container; they include InitializingBean and DisposableBean. Implementing these interfaces will result in the container calling afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction. www.intellibitz.com [email_address]
  • 98. Initialization Callbacks Implementing the org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean are set by the container. The InitializingBean interface specifies exactly one method: void afterPropertiesSet() throws Exception; www.intellibitz.com [email_address]
  • 99. Initialization Callbacks Generally, the use of the InitializingBean interface can be avoided (and is discouraged since it unnecessarily couples the code to Spring). A bean definition provides support for a generic initialization method to be specified. In the case of XML-based configuration metadata, this is done using the 'init-method' attribute. www.intellibitz.com [email_address]
  • 100. Initialization Callbacks <bean id=&quot;exampleInitBean&quot; class=&quot;examples.ExampleBean&quot; init-method=&quot;init&quot;/> public class ExampleBean { public void init() { // do some initialization work } } Is exactly the same as... <bean id=&quot;exampleInitBean&quot; class=&quot;examples.AnotherExampleBean&quot;/> public class AnotherExampleBean implements InitializingBean { public void afterPropertiesSet() { // do some initialization work } } ... but does not couple the code to Spring. www.intellibitz.com [email_address]
  • 101. Destruction Callbacks Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed. The DisposableBean interface specifies one method: void destroy() throws Exception; www.intellibitz.com [email_address]
  • 102. Destruction Callbacks <bean id=&quot;exampleInitBean&quot; class=&quot;examples.ExampleBean&quot; destroy-method=&quot;cleanup&quot;/> public class ExampleBean { public void cleanup() { // do some destruction work (like releasing pooled connections) } } Is exactly the same as... <bean id=&quot;exampleInitBean&quot; class=&quot;examples.AnotherExampleBean&quot;/> public class AnotherExampleBean implements DisposableBean { public void destroy() { // do some destruction work (like releasing pooled connections) } } ... but does not couple the code to Spring. www.intellibitz.com [email_address]
  • 103. Default initialization & destroy methods The Spring container can now be configured to 'look' for named initialization and destroy callback method names on every bean. www.intellibitz.com [email_address] public class DefaultBlogService implements BlogService { private BlogDao blogDao; public void setBlogDao(BlogDao blogDao) { this.blogDao = blogDao; } // this is (unsurprisingly) the initialization callback method public void init() { if (this.blogDao == null) { throw new IllegalStateException(&quot;The [blogDao] property must be set.&quot;); } } } <beans default-init-method=&quot;init&quot;> <bean id=&quot;blogService&quot; class=&quot;com.foo.DefaultBlogService&quot;> <property name=&quot;blogDao&quot; ref=&quot;blogDao&quot; /> </bean> </beans>
  • 104. BeanFactoryAware A class which implements the org.springframework.beans.factory.BeanFactoryAware interface is provided with a reference to the BeanFactory that created it, when it is created by that BeanFactory . public interface BeanFactoryAware { void setBeanFactory(BeanFactory beanFactory) throws BeansException; } This allows beans to manipulate the BeanFactory that created them programmatically, through the BeanFactory interface, or by casting the reference to a known subclass of this which exposes additional functionality. www.intellibitz.com [email_address]
  • 105. BeanNameAware If a bean implements the org.springframework.beans.factory.BeanNameAware interface and is deployed in a BeanFactory , the BeanFactory will call the bean through this interface to inform the bean of the id it was deployed under. The callback is invoked after population of bean properties but before initialization callback like afterPropertiesSet or a custom init-method. www.intellibitz.com [email_address]
  • 106. Bean definition inheritance A bean definition potentially contains a large amount of configuration information, including container specific information and constructor arguments and property values. A child bean definition is a bean definition that inherits configuration data from a parent definition. It is then able to override some values, or add others, as needed. Using parent and child bean definitions this way, is a form of templating. www.intellibitz.com [email_address]
  • 107. Bean definition inheritance a child bean definition is indicated simply by using the 'parent' attribute, specifying the parent bean as the value of this attribute. <bean id=&quot;inheritedTestBean&quot; abstract=&quot;true&quot; class=&quot;org.springframework.beans.TestBean&quot;> <property name=&quot;name&quot; value=&quot;parent&quot;/> <property name=&quot;age&quot; value=&quot;1&quot;/> </bean> <bean id=&quot;inheritsWithDifferentClass&quot; class=&quot;org.springframework.beans.DerivedTestBean&quot; parent=&quot;inheritedTestBean&quot; init-method=&quot;initialize&quot;> <property name=&quot;name&quot; value=&quot;override&quot;/> <!-- the age property value of 1 will be inherited from parent --> </bean> www.intellibitz.com [email_address]
  • 108. Bean definition inheritance <bean id=&quot;inheritedTestBeanWithoutClass&quot; abstract=&quot;true&quot;> <property name=&quot;name&quot; value=&quot;parent&quot;/> <property name=&quot;age&quot; value=&quot;1&quot;/> </bean> <bean id=&quot;inheritsWithClass&quot; class=&quot;org.springframework.beans.DerivedTestBean&quot; parent=&quot;inheritedTestBeanWithoutClass&quot; init-method=&quot;initialize&quot;> <property name=&quot;name&quot; value=&quot;override&quot;/> <!-- age will inherit the value of 1 from the parent bean definition--> </bean> www.intellibitz.com [email_address] The parent bean cannot get instantiated on its own since it is incomplete, and it is also explicitly marked as abstract. it is usable only as a pure template bean definition that will serve as a parent definition for child definitions. Trying to use such an abstract parent bean on its own (by referring to it as a ref property, or doing an explicit getBean() call with the parent bean id), will result in an error.
  • 109. BeanPostProcessor This interface defines a number of callback methods that you can implement in order to provide your own (or override the containers default) instantiation logic, dependency-resolution logic, and so forth. to do some custom logic after the Spring container has finished instantiating, configuring and otherwise initializing a bean, you can plug in one or more BeanPostProcessor implementations. www.intellibitz.com [email_address]
  • 110. BeanPostProcessor BeanPostProcessors operate on bean (or object) instances. If you want to change the actual bean definition, then you rather need to use a BeanFactoryPostProcessor . Also, BeanPostProcessors are scoped per-container. If you define a BeanPostProcessor in one container, it will only do its stuff on the beans in that container. www.intellibitz.com [email_address]
  • 111. PropertyPlaceholderConfigurer The PropertyPlaceholderConfigurer is used to externalize property values from a BeanFactory definition, into another separate file in the standard Java Properties format. This is useful to allow the person deploying an application to customize enviroment-specific properties, without the complexity or risk of modifying the main XML definition file or files for the container. www.intellibitz.com [email_address]
  • 112. PropertyPlaceholderConfigurer <bean class=&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;> <property name=&quot;locations&quot;> <value>classpath:com/foo/jdbc.properties</value> </property> </bean> <bean id=&quot;dataSource&quot; destroy-method=&quot;close&quot; class=&quot;org.apache.commons.dbcp.BasicDataSource&quot;> <property name=&quot;driverClassName&quot; value=&quot;${jdbc.driverClassName}&quot;/> <property name=&quot;url&quot; value=&quot;${jdbc.url}&quot;/> <property name=&quot;username&quot; value=&quot;${jdbc.username}&quot;/> <property name=&quot;password&quot; value=&quot;${jdbc.password}&quot;/> </bean> The actual values come from another file in the standard Java Properties format: jdbc.driverClassName=org.hsqldb.jdbcDriver jdbc.url=jdbc:hsqldb:hsql://production:9002 jdbc.username=sa jdbc.password=root www.intellibitz.com [email_address]
  • 113. The ApplicationContext Deriving from the BeanFactory interface, it provides all the functionality of BeanFactory. also provides the following functionality: MessageSource, providing access to messages in i18n-style Access to resources, such as URLs and files Event propagation to beans implementing the ApplicationListener interface Loading of multiple (hierarchical) contexts, allowing each to be focused on one particular layer, for example the web layer of an application www.intellibitz.com [email_address]
  • 114. Internationalization using MessageSources The ApplicationContext interface extends an interface called MessageSource, and therefore provides messaging (i18n or internationalization) functionality. Together with the HierarchicalMessageSource, capable of resolving hierarchical messages, these are the basic interfaces Spring provides to do message resolution. www.intellibitz.com [email_address]
  • 115. Internationalization using MessageSources When an ApplicationContext gets loaded, it automatically searches for a MessageSource bean defined in the context. The bean has to have the name messageSource. <beans> <bean id=&quot;messageSource&quot; class=&quot;org.springframework.context.support.ResourceBundleMessageSource&quot;> <property name=&quot;basenames&quot;> <list> <value>format</value> <value>exceptions</value> <value>windows</value> </list> </property> </bean> </beans> www.intellibitz.com [email_address]
  • 116. Events Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. If a bean which implements the ApplicationListener interface is deployed into the context, every time an ApplicationEvent gets published to the ApplicationContext, that bean will be notified. Essentially, this is the standard Observer design pattern. www.intellibitz.com [email_address]
  • 117. Events ContextRefreshedEvent Published when the ApplicationContext is initialized or refreshed. Initialized here means that all beans are loaded, singletons are pre-instantiated and the ApplicationContext is ready for use. www.intellibitz.com [email_address]
  • 118. Events ContextClosedEvent Published when the ApplicationContext is closed, using the close() method on the ApplicationContext. Closed here means that singleton beans (only!) are destroyed. www.intellibitz.com [email_address]
  • 119. Events RequestHandledEvent A web-specific event telling all beans that a HTTP request has been serviced (this will be published after the request has been finished). Note that this event is only applicable for web applications using Spring's DispatcherServlet. www.intellibitz.com [email_address]
  • 120. ApplicationContext for web You can register an ApplicationContext using the ContextLoaderListener as follows: <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- or use the ContextLoaderServlet instead of the above listener <servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> --> www.intellibitz.com [email_address]
  • 121. ApplicationContext for web The listener inspects the contextConfigLocation parameter. If it doesn't exist, it'll use /WEB-INF/applicationContext.xml as a default. When it does exist, it'll separate the String using predefined delimiters (comma, semi-colon and whitespace) and use the values as locations where application contexts will be searched for. The ContextLoaderServlet can be used instead of the ContextLoaderListener . www.intellibitz.com [email_address]
  • 122. Spring Summary The Spring IOC Container The BeanFactory and ApplicationContext Bean Scopes and Bean definition inheritance Customizing Beans with Callbacks BeanPostProcessors and Internationalization Events Configuring ApplicationContext for the web www.intellibitz.com [email_address]
  • 123. Resources Official Spring site: http://www.springframework.org Spring Documentation: http://www.springframework.org/documentation Spring Forum: http://forum.springframework.org www.intellibitz.com [email_address]
  • 124. About IntelliBitz Technologies http://training.intellibitz.com http://groups.google.com/group/etoe http://sted.sourceforge.net 168, Medavakkam Main Road, Madipakkam Chennai, 600091, India. +91 44 2247 5106 [email_address] www.intellibitz.com [email_address]
  • 125. Spring says Good Bye! Thank You! www.intellibitz.com [email_address]