Σχόλια 0

Το κείμενο του εγγράφου

Spring Framework Reference DocumentationWORK IN PROGRESS!!!Version:1.0Table of ContentsPreface................................................................................................................................................1.Introduction..................................................................................................................................1.1.Overview.............................................................................................................................11.2.Usage scenarios....................................................................................................................22.Background information...............................................................................................................2.1.Inversion of Control/Dependency Injection..........................................................................53.Beans and the ApplicationContext................................................................................................3.1.Introduction.........................................................................................................................63.2.BeanFactory and BeanDefinitions - the basics........................................................................63.2.1.The BeanDefinition...................................................................................................73.2.2.The BeanFactory.......................................................................................................73.2.3.The bean class...........................................................................................................73.2.4.The bean identifiers (id and name)..............................................................................83.2.5.To singleton or not to singleton..................................................................................83.3.Properties,dependencies and autowiring................................................................................83.3.1.Setting beans properties and collaborators...................................................................83.3.2.Autowiring collaborators............................................................................................103.3.3.Checking for dependencies.........................................................................................113.4.Customizing the nature of a bean...........................................................................................113.4.1.Lifecycle interfaces...................................................................................................113.4.2.Knowing who you are................................................................................................133.4.3.FactoryBean..............................................................................................................133.5.Interacting with the BeanFactory...........................................................................................133.6.Customizing the BeanFactory (advanced stuff).......................................................................143.6.1.The BeanFactoryPostProcessor...................................................................................143.6.2.The PropertyPlaceholderConfigurer............................................................................143.7.Lifecycle of a bean in the BeanFactory..................................................................................153.7.1.The basic lifecycle of a bean......................................................................................153.8.BeanFactory structure and implementations (WIP).................................................................173.8.1.Structure of the beans package...................................................................................183.8.2.The XmlBeanFactory.................................................................................................183.8.3.Bean definitions specified in XML (XmlBeanFactory).................................................183.9.Introduction to the ApplicationContext..................................................................................203.10.Added functionality of the ApplicationContext.....................................................................203.10.1.Using the MessageSource.........................................................................................203.10.2.Propagating events...................................................................................................213.10.3.Using resources within Spring..................................................................................223.11.Extra marker interfaces and lifecycle features.......................................................................233.12.Customization of the ApplicationContext.............................................................................234.PropertyEditors,data binding,validation and the BeanWrapper.................................................4.1.Introduction.........................................................................................................................244.2.Binding data using the DataBinder........................................................................................244.3.Bean manipulation and the BeanWrapper...............................................................................244.3.1.Setting and getting basic and nested properties............................................................254.3.2.Built-in PropertyEditors,converting types...................................................................264.3.3.Other features worth mentioning.................................................................................275.Spring AOP:Aspect Oriented Programming with Spring.............................................................5.1.Concepts..............................................................................................................................28Spring Framework 1.0 ii5.1.1.AOP concepts...........................................................................................................285.1.2.Spring AOP capabilities.............................................................................................295.1.3.AOP Proxies in Spring...............................................................................................305.1.4.Quick start................................................................................................................305.2.Pointcuts in Spring...............................................................................................................315.2.1.Concepts...................................................................................................................315.2.2.Operations on pointcuts.............................................................................................315.2.3.Convenience pointcut implementations.......................................................................325.2.4.Pointcut superclasses.................................................................................................335.2.5.Custompointcuts.......................................................................................................335.3.Advice types in Spring..........................................................................................................335.3.1.Advice lifecycles.......................................................................................................335.3.2.Advice types in Spring...............................................................................................345.4.Advisors in Spring................................................................................................................375.5.Using the ProxyFactoryBean to create AOP proxies...............................................................375.5.1.Basics.......................................................................................................................385.5.2.JavaBean properties...................................................................................................385.5.3.Proxying interfaces....................................................................................................385.5.4.Proxying classes........................................................................................................395.5.5.Special flags..............................................................................................................395.6.Convenient proxy creation....................................................................................................405.6.1.TransactionProxyFactoryBean....................................................................................405.6.2.EJB proxies...............................................................................................................405.7.Creating AOP proxies programmatically with the ProxyFactory..............................................415.8.Manipulating advised objects................................................................................................415.9.Using the"autoproxy"facility...............................................................................................425.9.1.Autoproxy bean definitions........................................................................................425.9.2.Using metadata-driven autoproxying...........................................................................445.10.Using TargetSources...........................................................................................................455.10.1.Hot swappable target sources....................................................................................455.10.2.Pooling target sources..............................................................................................455.10.3.Prototype"target sources..........................................................................................475.11.Defining new advice and advisor types................................................................................475.12.Further reading and resources..............................................................................................476.Transaction management..............................................................................................................6.1.The Spring transaction abstraction.........................................................................................486.2.Transaction strategies...........................................................................................................486.3.Programmatic transaction management..................................................................................486.4.Declarative transaction management......................................................................................486.5............................................................................................................................................487.Source Level Metadata Support....................................................................................................7.1.Source-level metadata...........................................................................................................497.2.Spring's metadata support.....................................................................................................497.3.Integration with Jakarta Commons Attributes.........................................................................497.4.Common uses of metadata attributes......................................................................................497.4.1.Declarative transaction management...........................................................................497.4.2.Pooling.....................................................................................................................497.4.3.Custommetadata.......................................................................................................497.4.4.Using attributes to minimize MVC web tier configuration............................................498.Data Access using JDBC...............................................................................................................8.1.Introduction.........................................................................................................................508.2.Using the JDBC Core classes to control basic JDBC processing and error handling..................50Spring Framework - J2EE Made EasySpring Framework 1.0 iii8.2.1.JdbcTemplate............................................................................................................508.2.2.SQLExceptionTranslator............................................................................................518.3.Controling how we connect to the database............................................................................518.3.1.DataSourceUtils........................................................................................................518.3.2.SmartDataSource.......................................................................................................518.3.3.AbstractDataSource...................................................................................................518.3.4.SingleConnectionDataSource.....................................................................................518.3.5.DriverManagerDataSource.........................................................................................518.3.6.DataSourceTransactionManager.................................................................................518.4.Modeling JDBC operations as Java objects............................................................................518.4.1.SqlQuery..................................................................................................................528.4.2.MappingSqlQuery.....................................................................................................528.4.3.SqlUpdate.................................................................................................................528.4.4.StoredProcedure........................................................................................................528.4.5.SqlFunction...............................................................................................................529.Web framework............................................................................................................................9.1.Introduction to the web framework........................................................................................539.1.1.Pluggability of MVC implementation.........................................................................539.1.2.Features of Spring MVC............................................................................................549.2.The DispatcherServlet..........................................................................................................549.3.Controllers...........................................................................................................................569.3.1.Using the AbstractController and WebContentGenerator..............................................579.3.2.Other simple controller..............................................................................................589.3.3.The MultiActionController.........................................................................................589.3.4.CommandControllers.................................................................................................609.4.Handler mappings................................................................................................................619.4.1.BeanNameUrlHandlerMapping..................................................................................619.4.2.SimpleUrlHandlerMapping........................................................................................629.4.3.Adding HandlerInterceptors.......................................................................................639.5.Views and resolving them.....................................................................................................649.5.1.ViewResolvers..........................................................................................................649.6.Using locales.......................................................................................................................659.6.1.AcceptHeaderLocaleResolver.....................................................................................669.6.2.CookieLocaleResolver...............................................................................................669.6.3.SessionLocaleResolver..............................................................................................669.6.4.LocaleChangeInterceptor...........................................................................................669.7.Using themes.......................................................................................................................679.8.Spring's multipart (fileupload) support...................................................................................679.8.1.Introduction..............................................................................................................679.8.2.Using the MultipartResolver.......................................................................................679.8.3.Handling a fileupload in a form..................................................................................689.9.Handling exceptions.............................................................................................................709.10.Commonly used utilities.....................................................................................................709.10.1.A little story about the pathmatcher...........................................................................7010.Integrating view technologies......................................................................................................10.1.Introduction.......................................................................................................................7110.2.Velocity.............................................................................................................................7110.2.1.Dependencies..........................................................................................................7110.2.2.Dispatcher Servlet Context.......................................................................................7110.2.3.Velocity.properties..................................................................................................7210.2.4.View configuration..................................................................................................7310.2.5.Creating the Velocity templates................................................................................74Spring Framework - J2EE Made EasySpring Framework 1.0 iv10.2.6.FormHandling........................................................................................................7410.2.7.Summary................................................................................................................7610.3.XSLT Views......................................................................................................................7610.3.1.My First Words.......................................................................................................7610.3.2.Summary................................................................................................................7810.4.Document views (PDF/Excel).............................................................................................7910.4.1.Introduction.............................................................................................................7910.4.2.Configuration and setup...........................................................................................7910.5.Tapestry.............................................................................................................................8110.5.1.Architecture............................................................................................................8110.5.2.Implementation.......................................................................................................8110.5.3.Summary................................................................................................................8610.6.Tiles..................................................................................................................................8710.6.1.Configuration..........................................................................................................8710.6.2.Summary................................................................................................................8711.Accessing and implementing EJBs..............................................................................................11.1.Accessing EJBs..................................................................................................................8811.1.1.Concepts.................................................................................................................8811.1.2.Accessing local SLSBs............................................................................................8811.1.3.Accessing remote SLSBs.........................................................................................8811.2.Using Spring convenience EJB implementation classes.........................................................8812.Sending Email with Spring mail abstraction layer.......................................................................12.1.Introduction.......................................................................................................................8912.2.Spring mail abstraction structure.........................................................................................8912.3.Using Spring mail abstraction..............................................................................................9012.3.1.Pluggable MailSender implementations.....................................................................92A.Spring's beans.dtd..........................................................................................................................Spring Framework - J2EE Made EasySpring Framework 1.0 vPrefaceDeveloping applications alone is hard already,implementing applications using platforms that promise every-thing but turn out to be heavy-weight,hard to control and not very efficient during development cycles makes iteven harder.Spring provides a light-weight solution to build enterprise-ready applications,still supporting thepossibility of having declarative transaction management,remote access to your logic using RMI or webser-vices,mailing facilities and a decent way of persisting your data in a database.Spring provides an MVC frame-work,transparent ways of integrating AOP in your software and a well-structured exception hierarchy for forexample JDBC.Spring could potentially be a one-stop-shop for all your enterprise applications,however,Spring is modular,al-lowing you to use parts of it,without bothering about the rest.You can use the bean container,with Struts ontop,but you could also choose to just use the Hibernate integration or the JDBC abstraction layer.Spring isnon-intrusive,meaning you can do without any dependencies on the framework at all,thus not tying yourself into Spring.This document provides a reference guide to Spring's features.Since this document is still work-in-progress,you if you have any requests,comments,please post them on the userlist or on the forum at the SourceForgeproject page:http://www.sf.net/projects/springframeworkBefore we go on a couple some words of gratitude.Chris Bauer (Hibernate) prepared and adapted the Doc-Book-XSL software in order to be able to create Hibernate's reference guide,also allowing us to create this one.Spring Framework 1.0 viChapter 1.Introduction1.1.OverviewSpring contains a lot of functionality and features,which are well-organized in seven modules shown in the dia-grambelow.This section discusses each the of modules in turn.Overview of the the Spring FrameworkThe beans package is the most fundamental part of the framework and provides the Dependency Injection fea-tures allowing you to manage beans containing functionality.The basic concept here is the BeanFactory,whichprovides a factory pattern removing the need for programmatic singletons and allowing you to decouple theconfiguration and specification of dependencies fromyour actual logic.On top of the beans package sits the context package,providing a way to access beans in a framework-stylemanner,somewhat resembling a JNDI-registry.The context package inherits its features from the beans pack-age and adds messaging,event-propagation,resource-loading and transparent creation of contexts by,for exam-ple,a servlet container.The JDBC package provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding andparsing database-vendor specific error codes.Also,the JDBC package provides a way to do programmatic aswell as declarative transaction management,not only for classes implementing special interfaces,but for allyour POJOs.The ORM package provides integration layers for popular object-relational mappers,including JDO,Hibernateand iBatis.Using the ORM package you can use all those O/R-mappers in combination with all the other fea-tures Spring offers,like simple declarative transaction management mentioned before.Spring's AOP package provides an Aop Alliance compliant aspect-oriented programming implementing allow-ing you to define,for example,method-interceptors and pointcuts to cleanly decouple code implementing func-tionality that should logically speaking be separated.Using source-level metadata functionality you can incor-porate all kinds of behavioral information in your code,a little like.NET attributes.Spring Framework 1.0 1Spring's web package provides the basic web-oriented integration features,like multipart functionality,initial-ization of contexts using servlet listeners and a web-oriented application context.When using Spring togetherwith WebWork or Struts,this is the package to integrate with.Spring web MVC package provides a Model-View-Controller implementation for web-applications.Spring'sMVC implementation is not just any implementation,it provides a clean separation between domain modelcode and web forms and allows you to use all the other features of the Spring Framework like validation.1.2.Usage scenariosWith the building block described above you can use Spring in all sorts of scenarios,from applets up to fully-fledged enterprise application using Spring's transaction management functionality and for example Spring'sWeb framework.Typical full-fledged Spring web applicationA typical web application using most of Spring's features.Using TransactionProxyFactoryBeans the web ap-plication is fully transactional,just as it would be when using container managed transaction as provided by En-terprise JavaBeans.All your custom business logic can be implemented using simple POJOs,managed bySpring's Dependency Injection container.Additional services like sending email and validation,independent ofthe web-layer enable you to choose where to execute validation rules.Spring's ORMsupport is integrated withHibernate,JDO and iBatis.Using for example HibernateDaoSupport,you can re-use your existing Hibernatemappings.Form controllers seamlessly integrate the web-layer with the domain model,removing the need forActionForms or other classes that transformHTTP parameters to values for your domain model.IntroductionSpring Framework 1.0 2Spring middle-tier using a third-party web frameworkSometimes the situation does not allow you completely switch to a different framework.Spring does not en-force you to use everything,it's not an all-or-nothing solution.Existing frontends using WebWork or Struts canbe integrated perfectly well with a Spring-based middle-tier,allowing you to use the transaction features thatSpring offers.The only thing you need to do is wire up your business logic using an ApplicationContext andintegrating your Struts frontend using a WebApplicationContext.Remoting usage scenarioWhen you need to access existing code via webservices,you can use Spring's Hessian-,Burlap-,Rmi- orJaxRpcProxyFactory classes.Enabling remote access to existing application is all of a sudden not that hardanymore.IntroductionSpring Framework 1.0 3EJBs - Wrapping existing POJOsSpring also provide an access-layer and abstraction-layer for Enterprise JavaBeans,enabling you to reuse yourexisting POJOs and wrap them in Stateless SessionBeans,for use in scalable failsafe webapplications,thatmight need declarative security.IntroductionSpring Framework 1.0 4Chapter 2.Background information2.1.Inversion of Control/Dependency InjectionIn early 2004,Martin Fowler asked the readers of his site:when talking about Inversion of Control:"the ques-tion,is what aspect of control are they inverting?".After talking about the term Inversion of Control Martinsuggests renaming the pattern,or at least giving it a more self-explanatory name,and starts to use the term De-pendency Injection.His article continues to explain some of the ideas behind Inversion of Control or Depen-dency Injection.If you need a decent insight:http://martinfowler.com/articles/injection.html.Spring Framework 1.0 5Chapter 3.Beans and the ApplicationContext3.1.IntroductionTwo of Spring's most elementary and important packages are the org.springframework.beans andorg.springframework.context package.These packages provide the basis for the Spring Inversion of Controlfeatures,or Dependency Injection as people more recently call it (see Section 2.1,Inversion of Control/De-pendency Injection for some resources on that).The BeanFactory provides an advanced configuration mecha-nismcapable of managing beans of any kind of nature,using - potentially - any kind of storage facility.The Ap-plicationContext builds on top of the BeanFactory and adds other functionality such as integration withSprings AOP features,messaging (using i18n),the capability of having contexts inherit fromother contexts anddefining application-layer specific contexts,such as the WebApplicationContext.In short,the BeanFactory provides the configuration framework and allows you to for example avoid the use ofsingletons,while the ApplicationContext adds more enterprise-centric,J2EE functionality to it.This chapter is roughly divided into two parts,the first part covering the basic principles that apply to both theBeanFactory and the ApplicationContext.The second part will cover some of the features that only apply to theApplicationContext.In order to get you started using the BeanFactory and the ApplicationContext we'll first introduce you to a cou-ple of basic principles that might be handy to know of when using the BeanFactory and the ApplicationContext. Bean definition:the description of a bean managed by the BeanFactory.Each BeanFactory contains beandefinitions each describing the nature of a bean,its properties,the methods that need to be called upon ini-tialization and destruction,whether or not the bean needs to be autowired and more things a like.The Xml-BeanFactory for example is capalbe of reading bean definitions from an XML file,where properties,aswell as collaborators and lifecycle methods are defined in XML Property editors:part of the JavaBeans specification by Sun is the concept of PropertyEditors.Propertyeditors in Spring are used to convert properties of beans to human-readable String and vice versa.As thePropertyEditor JavaDOC (http://java.sun.com/j2se/1.4.2/docs/api/) states,the getAsText()-method shouldreturn a human-readable String representing the property the editor is (so-called) editing.The setAsText()-method should be able to parse the same String and (using the setValue(Object)-method) set the resultingvalue of the property.PropertyEditors are heavily used in Spring,not only by for example the BeanFactoryto transform the Strings defined in the XML containing beans to properties of those beans,but also by theMVC framework to convert request parameters submitted by a user after filling a form to properties ofcommand objects that might be of some completely different type BeanWrapper:an special class of which instances wrap a bean,managed BeanWrappers for example havefeatures for setting and getting properties from the beans they're wrapping.It's not likely you'll ever have totouch a BeanWrapper yourself,but it might be handy to know about themNote:there has been a lot of confusion about the use of the ApplicationContext as opposed to the BeanFactory.Basically when building applications in a J2EE-environment you're the better option would be to use the Appli-cationContext,since it offers a more framework style usage of the Spring Framework and can be initialized us-ing a ServletContextListener like the ContextLoaderListener.3.2.BeanFactory and BeanDefinitions - the basicsSpring Framework 1.0 63.2.1.The BeanDefinitionAs already stated in the introduction,bean definitions describe beans managed by a BeanFactory or Applica-tionContext.Bean definitions contain the following information: The beanclass,which is the actual implementation of the bean related to the bean definition Bean behavioral configuration elements,which state how the bean should behave in the container (i.e.pro-totype or singleton,autowiring mode,dependency checking mode,initialization and destruction methods) Properties being configuration data for the bean.You could think of the number of connections to use in abean that manages a connection pool (either specified as properties or as constructor arguments),or theclass that should be used to create the connection pool Other beans your bean needs to do its work,i.e.collaborators (also specified as properties or as constructorarguments)In the list above,we mentioned the use of constructor arguments,as well as setters.Spring support two types ofIoC,i.e.type 2 and type 3.What that means is that you use both constructor arguments to specify your depen-dencies and properties as well as setters and getters.The concepts listed above,directly translate to a set of elements the bean definition consists of.These elementsare listed below,along with a reference to further documentation about each of them.Table 3.1.Bean definition explanationFeatureMore infoclassSection 3.2.3,The bean classsingleton or prototypeSection 3.2.5,To singleton or not to singletonbean propertiesSection 3.3.1,Setting beans properties and collaboratorsconstructor argumentsSection 3.3.1,Setting beans properties and collaboratorsautowiring modeSection 3.3.2,Autowiring collaboratorsdependency checking modeSection 3.3.3,Checking for dependenciesinitialization methodSection 3.4.1,Lifecycle interfacesdestruction methodSection 3.4.1,Lifecycle interfaces3.2.2.The BeanFactoryThe BeanFactory is the actual container (although we don't like to use the word container too much,since itkind of sounds quite heavy),containing and managing your beans.A BeanFactory loads BeanDefinitions and -upon request - instantiates one (or possibly more) instances of the bean in question and manages it by callinglifecycle methods.All of the features described in Section 3.2.1,The BeanDefinition will be configurable for each of your beansusing one of the out-of-the-box BeanFactory implementations.In the example below we will use the most pop-ular BeanFactory to illustrate the behavior,i.e.the XmlBeanFactory.More information on the XmlBeanFactoryand other implementations can be found further ahead.3.2.3.The bean classBeans and the ApplicationContextSpring Framework 1.0 7Of course you need to specify the actual class of your bean,that should be obvious.There's absolutely no spe-cial requirements to your beanclass,it does not have to implement a special interface to make it Spring compat-ible.Just specifying the bean class should be enough.However,dependending on what type of IoC you are go-ing to use for that specific bean,you should have a default constructor.The BeanFactory cannot only manage beans,but is able to manage virtually any class you want it to manage.Most people using Spring prefer to have actual beans (having just a default constructor and appropriate settersand getters modelled after the properties) in the BeanFactory,but it it's also possible to have more exotic non-bean-style classes in your BeanFactory.If,for example,you're having a legacy connection pool that absolutelydoes not adhere to the bean specification,no worries,Spring can manage it as well.Using the XmlBeanFactory you can specify your bean class as follows:<bean id="exampleBean"class="examples.ExampleBean"/><bean name="anotherExample"class="examples.ExampleBeanTwo"/>3.2.4.The bean identifiers (id and name)Somehow of course you need to identifiy your beans.This can be done by a name or an id.The id is to beuniquely defined across all beans in a BeanFactory.3.2.5.To singleton or not to singletonBeans exist in two types,singletons and prototypes.When a bean is a singleton,only one shared instance of thebean will be managed and all requests for instances of that specific instances of bean will result in that one spe-cific bean instance being returned.The prototype mode of a bean results in creation of a new bean instance every time a request for that specificbean is being done.This is ideal for situation where for example each user needs an independent user object orsomething similar.Beans exist in singleton mode by default,unless you specify otherwise.Keep in mind that by changing the typeto prototype,each request for a bean will result in a newly created bean and this might not be what you actuallywant.So only change the mode to prototype when absolutely necessary.In the example below,two beans are declared of which one is defined as a singleton,and the other one as a pro-totype.exampleBean is created each and every time a client asks the BeanFactory for this bean,while yetAn-otherExample is only created one,a reference is returned each time a request for this bean is done.<bean id="exampleBean"class="examples.ExampleBean"singleton="false"/><bean name="yetAnotherExample"class="examples.ExampleBeanTwo"singleton="true"/>3.3.Properties,dependencies and autowiring3.3.1.Setting beans properties and collaboratorsInversion of Control has already been referred to as Dependency Injection.The basic principle is that beansBeans and the ApplicationContextSpring Framework 1.0 8themselves do not define who or what they're depending on,but instead,let the container do that for them.Also,the container injects the actual dependencies,as opposed to the Service Locator pattern,where the beansthemselves do a lookup to resolve those dependencies.While not elaborating too much on the advantages ofDependency Injection,it might be obvious that code gets much cleaner and reaching a higher grade of decou-pling is much easier when beans themselves do not lookup their dependencies,but also do not even knowwhere the actual dependencies are located and of what actual instance they are.The BeanFactory is capable of injecting dependencies into beans its manages.It does so using the BeanDefini-tion and the PropertyEditors that are defined in the Spring Framework.We'll explain that further along usingsome examples of beans defined in the XML format.For now it might be handy to know that BeanDefinitions,collaborators and properties are specified using PropertyValue-objects.The resolving of the dependencies is a little too complex to go in depth here,but the basic procedure is as fol-lows:1.Checking what the type of the property is (this can be a primitive-like type - like int or String,a Collection- i.e.Map or List,a Class or any other type Spring supports by default.It can also be a collaborator).Col-laborators are other beans the BeanFactory must capable of resolving,in order words,other beans,also de-fined in the same BeanFactory (or,in case you're using the ApplicationContext,possibly in another appli-cation context)2.In case the bean isn't a collaborator that can be resolved from the BeanFactory,Spring uses its built-in (ormanually added) PropertyEditors to transform the property to the type that was required (when using theXML format to define a bean that contains a setter with a Class-parameter,Spring uses the ClassEditor(more about PropertyEditors and how to manually add custom ones,can be found further ahead,TODODODODODODO reference!)3.In the case of collaborators,Spring constructs a reference to the bean that is used later on when the bean isactually instantiated.You can trust Spring here that it sets the actual collaborator at the right moments.Dependency Injection (or Inversion of Control) exists in two major variants,both of which Spring supports. setter-based dependency injection is realized by calling setters on your beans after invoking an argument-less constructor to instantiate your bean.Beans defined in the BeanFactory that use setter-based dependencyinjection are true JavaBeans,and not only for the sake of adhering a standard,Spring advocated to use set-ter-based dependency injection as much as possible constructor-based dependency injection is realized by invoking a constructor with a number of arguments,each representing a collaborator or property.Though Spring advices to use setter-based dependency injec-tion as much as possible,there might be beans around that just have constructors and that you want to useas well.Therefore we provided the constructor-based approach as wellSome examples:First,an example of using the BeanFactory for setter-based dependency injection.Below,there's a small part ofan XML file specifying bean definition.Also,you can find the actual bean itself,having the appropriate settersdeclared.<bean id="exampleBean"class="examples.ExampleBean"><property name="beanOne"><ref bean="anotherExampleBean"/></property><property name="beanTwo"><ref bean="yetAnotherBean"/></property><property name="integerProperty">1</property></bean><bean id="anotherExampleBean"class="examples.AnotherBean"/><bean id="yetAnotherBean"class="examples.YetAnotherBean"/>public class ExampleBean {Beans and the ApplicationContextSpring Framework 1.0 91See Section 3.3.1,Setting beans properties and collaborators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;}}As you can see,setters have been declared to match against the properties specified in the XML file.(The prop-erties fromthe XML file,directly relate to the PropertyValues object fromthe RootBeanDefinition)Then,an example of using the BeanFactory for IoC type 3 (using constructors).Below you can find a snippetfrom an XML configuration file that specifies constructor arguments and the actual bean,specifying the con-structor<bean id="exampleBean"class="examples.ExampleBean"><constructor-arg><ref bean="anotherExampleBean"/></constructor-arg><constructor-arg><ref bean="yetAnotherBean"/></constructor-arg><constructor-arg>1</constructor-arg></bean><bean id="anotherExampleBean"class="examples.AnotherBean"/><bean id="yetAnotherBean"class="examples.YetAnotherBean"/>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;}}As you can see,the constructor arguments specified in the bean definition will be used to pass in as argumentsto the constructor of the ExampleBean.3.3.2.Autowiring collaboratorsSpring has autowire capabilities,which means it's possible to automatically let Spring resolve collaborators(other beans) for you bean by inspecting the BeanFactory.The autowiring functionality has four modes.Au-towiring is specified per bean and can thus be enabled for a couple of beans,while other beans won't be au-towired.When using autowiring,there might be no need for specifying properties or constructor arguments1Table 3.2.Autowiring modesBeans and the ApplicationContextSpring Framework 1.0 10ModeExplanationnoNo autowiring at all.This is the default value and it's discouraged to change this for largeapplications,since specifying your collaborators yourself gives you a feeling of whatyou're actually doing and is a great way of somewhat documenting the structure of yoursystembyNameThis option will inspect the BeanFactory and look for a bean named exactly the same asthe property which needs to be autowired.So in case you have a collaborator on a Bean-Definition Cat which is called dog (so you have a setDog(Dog) method),Spring will lookfor a BeanDefinition named dog and use this as the collaboratorbyTypeThis option can be found in some other IoC containers as well and gives you the ability toresolve collaborators by type instead of by name.Suppose you have a BeanDefinition witha collaborator typed DataSource,Spring will search the entire bean factory for a bean defi-nition of type DataSource and use it as the collaborator.If 0 (zero) or more than 1 (one)bean definitions of the desired type exist in the BeanFactory,a failure will be reported andyou won't be able to use autowiring for that specific beanNote:like already mentioned,for larger applications,it is discouraged to use autowiring because it removesthe transparency and the structure from your collaborating classes.3.3.3.Checking for dependenciesSpring also offers the capability for checking required dependencies of your beans.This feature might come inhandy when certain properties really need to be set and when you can't provide default values (which is an of-ten used approach).Dependency checking can be done in three different ways.Dependency checking can alsobe enabled and disabled per bean,just as the autowiring functionality.The default is to not check dependencies.Table 3.3.Dependency checking modesModeExplanationsimpleDependency checking is done for primitive types and collections (this means everythingexcept collaborators)objectDependency checking is done for collaboratorsallDependecny checking is done for both collaborators and primitive types and collections3.4.Customizing the nature of a bean3.4.1.Lifecycle interfacesSpring provides a couple of marker interfaces to change the behavior of your bean in the BeanFactory.They in-clude InitializingBean and DisposableBean.Implementing those will result in the BeanFactory calling af-terPropertiesSet() for the former and destroy() for the latter to allow you to do things upon initializationand destruction.Internally,Spring uses BeanPostProcessors to process any marker interfaces it can find and call the appropri-ate methods.If you need custom features or other lifecycle behavior Spring doesn't offer out-of-the-box,youBeans and the ApplicationContextSpring Framework 1.0 11can implement a BeanFactoryPostProcessor yourself.More information about this can be found in Sec-tion 3.6.1,The BeanFactoryPostProcessor.All the different lifecycle marker interfaces are described below.In one of the appendices,you can find dia-gram as to how Spring manages beans and how those lifecycle features change the nature of your beans andhow they are managed.3.4.1.1.InitializingBean/init-methodThe org.springframework.beans.factory.InitializingBean gives you the ability the do initialization workafter all necessary properties on a bean are set by the BeanFactory.The InitializingBean interface specifies ex-actly one method: void afterPropertiesSet():called after all properties have been set by the beanfactory.This method en-ables you to do checking to see if all necessary properties have been set correctly,or to perform further ini-tialization work.You can throw any exception to indicate misconfiguration,initialization failures,etceteraNote:generally,the use of the InitializingBean can be avoided (and by some people is discouraged).Thebeans package provides support for a generic init-method,given to the beandefinition in the beanconfigurationstore (may it be XML,properties-files or a database).<bean id="exampleInitBean"class="examples.ExampleBean"init-method="init()"/>public class ExampleBean {public void init() {//do some initialization work}}Is exactly the same as:<bean id="exampleInitBean"class="examples.AnotherExampleBean"/>public class AnotherExampleBean implements InitializingBean {public void afterPropertiesSet() {//do some initialization work}}3.4.1.2.DisposableBean/destroy-methodThe org.springframework.beans.factory.DisposableBean interface provides you with the ability to get acallback when a beanfactory is destroyed.The DisposableBean interface specifies one method: void destroy():called on destruction of the beanfactory.This allows you to release any resources you arekeeping in this bean (like database connections).You can throw an exception here,however,it will not stopthe destruction of the bean factory.It will get logged though.Note:generally,the use of the DisposableBean can be avoided (and by some people is discouraged).Thebeans package provides support for a generic destroy-method,given to the beandefinition in the beanconfigu-ration store (may it be XML,properties-files or a database).For more information about this feature,see thenext section)<bean id="exampleInitBean"class="examples.ExampleBean"destroy-method="cleanup()"/>Beans and the ApplicationContextSpring Framework 1.0 12public class ExampleBean {public void cleanup() {//do some destruction work (like closing connection)}}Is exactly the same as:<bean id="exampleInitBean"class="examples.AnotherExampleBean"/>public class AnotherExampleBean implements DisposableBean {public void destroy() {//do some destruction work}}3.4.2.Knowing who you are3.4.2.1.BeanFactoryAwareThe org.springframework.beans.factory.BeanFactoryAware interface gives you the ability to get a refer-ence to the BeanFactory that manages the bean that implements the BeanFactoryAware interface.This featureallows for implementing beans to look up their collaborators in the beanfactory.The interface specifies onemethod: void setBeanFactory(BeanFactory):method that will be called after the initialization methods (after-PropertiesSet and the init-method).3.4.2.2.BeanNameAwareThe org.springframework.beans.factory.BeanNameAware interface gives you the ability to let the BeanFac-tory set the name of the bean on the bean itself.In case you need to know what your name is,implement this in-terface void setBeanName(String):method which will be called to let the bean know what its name is3.4.3.FactoryBeanThe org.springframework.beans.factory.FactoryBean is to be implemented objects that are themselves fac-tories.The BeanFactory interface provides three method: Object getObject():has to return an instance of the object this factory creates.The instance can possiblybe shared (depending on this factory providing singleton or prototypes). boolean isSingleton():has to return true if this FactoryBean returns singletons,false otherwise Class getObjectType():has to return either the object type returned by the getObject() method or nullif the type isn't known in advance3.5.Interacting with the BeanFactoryBasically the BeanFactory is nothing more than an advanced factory capable of maintaining a registry oof dif-ferent components or beans.The BeanFactory enables you to read bean definitions and access them using theBeans and the ApplicationContextSpring Framework 1.0 13bean factory.When just using the BeanFactory you would create one and read in some bean definitions in theXML format as follows:InputStream is = new FileInputStream("beans.xml");XmlBeanFactory factory = new XmlBeanFactory(is);Basically that's all there is to it.Using getBean(String) you can retrieve instances of your beans.You'll get areference to the same bean if you defined it as a singleton (which is the default) and you'll get a new instanceeach time if you set singleton to false.The client-side view of the BeanFactory is surprisingly simple.TheBeanFactory interface four methods for clients to interact with it: Object getBean(String):returns an instance of the bean registered under the given name.Depending onhow the bean was configured by the beanfactory configuration,a singleton and thus shared instance will bereturned,or a newly created bean.A BeansException will be thrown when either the bean could not befound (in which case it'll be a NoSuchBeanDefinitionException),or an exception occured while instanti-ated and preparing the bean Object getBean(String,Class):returns a bean,registered under the given name.The bean returned willbe cast to the given Class.If the bean could not be cast,corresponding exceptions will be thrown (Bean-NotOfRequiredTypeException).Furthermore,all rules of the getBean(String) method apply (see above) boolean isSingleton(String):determines whether or not the beandefinition registered under the givenname is a singleton or a prototype.If the beandefinition corresponding to the given name could not befound,an exception will be thrown (NoSuchBeanDefinitionException) String[] getAliases(String):returns the aliases configured for this bean (TODO:WHAT IS THIS:)3.6.Customizing the BeanFactory (advanced stuff)When in need for special behavior for the BeanFactory you need to consult theorg.springframework.beans.factory.config-package,which should provide you all the things you need insuch a case.Using the config package you can for instance define a properties file of which the property-entriesare used as replacements values in the BeanFactory.Also,you can implement custom behavior (like addingcustom editors) using the BeanFactoryPostProcessor.Each of the features the config-package offers is de-scribed below:3.6.1.The BeanFactoryPostProcessorThe BeanFactoryPostProcessor is the superclass for all post processors that are capable of applying changes tothe BeanFactory (or beans in it) after the factory has been initialized.The BeanFactoryPostProcessor can beused to add custom editors (as also mentioned in Section 4.3.2,Built-in PropertyEditors,converting types).Some out-of-the-box post processors are available,like the PropertyResourceConfigurer and the Property-PlaceHolderConfigurer,both described below.3.6.2.The PropertyPlaceholderConfigurerThe PropertyPlaceholderConfigurer is an excellent solution when you want to externalize a few propertiesfrom a file containing bean definitions.Say you want to let the person responsible for deploying applicationsjust fill in database URLs,usernames and passwords.You could of course let him change the XML file con-taining bean definitions,but that would be risky.Instead,use the PropertyPlaceHolderConfigurer to - at run-time - replace those properties by values froma properties file.Beans and the ApplicationContextSpring Framework 1.0 14In the example below,a datasource is defined,and we will configure some properties from an external Proper-ties file.At runtime,we will apply a PropertyPlaceholderConfigurer to the BeanFactory which will replacesome properties of the datasource:<bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName"><value>${jdbc.driverClassName}</value></property><property name="url"><value>${jdbc.url}</value></property><property name="username"><value>${jdbc.username}</value></property><property name="password"><value>${jdbc.password}</value></property></bean>jdbc.driverClassName=org.hsqldb.jdbcDriverjdbc.url=jdbc:hsqldb:hsql://production:9002jdbc.username=sajdbc.password=root=XmlBeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml"));Properties props = new Properties();props.load(new FileInputStream("jdbc.properties"));PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(props);cfg.postProcessBeanFactory(factory);3.7.Lifecycle of a bean in the BeanFactoryThis section describes the lifecycle of a bean in the BeanFactory,some of the basic characteristics of eventshappening in the BeanFactory as well as the different types of beans.3.7.1.The basic lifecycle of a beanThe lifecycle of a bean begins with a bean definition,for instance defined in XML or a properties file.The firststep is the calling of the default constructor:1.default constructorThe second step is the initialization process in which you can prepare your bean for use.2.the autowiring process in which any possible collaborators that can be automatically resolved,will be set(TODO:reference)3.checking of dependencies,which means that if dependencies are unsatisfied (i.e.they are null),an Unsat-isfiedDependencyException will be thrown.(TODO:reference)4.property setting,which means that all properties defined with the bean definition in for instance an XMLfile,will be set on the bean5.afterPropertiesSet() is called.This method is specified by the InitializingBean,and thus will onlybe called if your bean implements this interface (TODO:reference)6.the extra initialization method will be called that might have been specified with the bean definition(TODO:reference)7.if your bean is BeanFactoryAware the setBeanFactory() method will now be called enabling the bean tohave access to the BeanFactory (TODO:reference)Right now,your bean is ready for use.Calls to BeanFactory.getBean() with the name of the bean,will resultBeans and the ApplicationContextSpring Framework 1.0 15in an instance of that bean being returned.Depending on whether or not this bean is a singleton,a shared in-stance will be returned.More information on consequences for singletons can be found below.When the BeanFactory gets destroyed (for instance when the application server shuts down),the destructionprocess of the BeanFactory will try to destroy all beans that it knows about.The destruction process will onlyoccur for singletons beans.8.If your bean implements DisposableBean the BeanFactory will call destroy()9.If you bean definition includes a destroy method declaration,this method will be called as wellA diagramillustrating the lifecycle of a bean:Beans and the ApplicationContextSpring Framework 1.0 163.8.BeanFactory structure and implementations (WIP)From here on,up till the Context stuff,needs an overhaul.The beans package contains a couple of different implementations.Concrete BeanFactories include the Xml-Beans and the ApplicationContextSpring Framework 1.0 17BeanFactory which is the most popular format at the moment.However,the ListableBeanFactory is also anice one,which is capable of reading bean definitions fromproperties files.3.8.1.Structure of the beans packageInclude UML and description here3.8.2.The XmlBeanFactoryThe XmlBeanFactory is the most often-used implementation of the BeanFactory and is capable of reading beandefinitions fromXML files.XML files need to adhere to the Spring DTD,included in AppendixA couple of implementations of the BeanFactory come out-of-the-box.The XmlBeanFactory supports a beandefinitions to be specified in XML files and the ListableBeanFactory supports bean definitions in the form ofproperties files.Most people use the XmlBeanFactory.However,implementing your own BeanFactory thatsupports bean definition in a database should not be to big an issue.Let's first discuss the XmlBeanFactory andthe ListableBeanFactory and their features.Basically the two BeanFactory implementations Spring comes with provide all the features described above,like specifying the lifecycle methods,specifying whether or not to do autowiring,etcetera.The only way theydiffer is the way the configuration data (the bean definitions) are stored.3.8.3.Bean definitions specified in XML (XmlBeanFactory)One of the implementations of the BeanFactory is the XmlBeanFactory (located in the packageorg.springframework.beans.factory.xml) which offers you the ability to specify bean definition in XMLfiles as the name might have already told you.Spring comes with a DTD to do validation of the XML you'rewriting to specify beans in order to make things a bit more easy.The DTD is quite well documented so youshould find everything you need in there as well.Here we will discuss the format shortly and provide some ex-amples.The root of a Spring XML bean definition document is a <beans> element.The <beans> element contains oneor more <bean> definitions.We normally specify the class and properties of each bean definition.We must alsospecify the id,which will be the name that we'll use this bean with in our code (see a previous section aboutclients interacting with the BeanFactory for more information.An initialization method as described earlier aswell the destruction method can be specified as attributes of the <bean> element.The autowiring functionalityas well as the de dependency checking can also be specified using attributes of the same element.Furthermoreproperties and collaborators can be specified using nested <property> elements.In the following example,weuse a BasicDataSource from the Jakarta Commons DBCP project.This class (like many other existing classes)can easily be used in a Spring bean factory,as it offers JavaBean-style configuration.The close method thatneeds to be called on shutdown can be registered via Spring's destroy-method attribute,to avoid the need forBasicDataSource to implement any Spring interface (in this case that would be DisposableBean mentioned ear-lier in the section about lifecycle features).<beans><bean id="myDataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><!-- results in a setDriverClassName(String) call --><property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property><property name="url"><value>jdbc:mysql://localhost:3306/mydb</value></property>Beans and the ApplicationContextSpring Framework 1.0 18<property name="username"><value>root</value></property></bean></beans>Just as an destruction method is specified using the destroy-method attribute,we could specify a initializationmethod using the init-method attribute.To specify properties and collaborators in XML files you have to use nested <property> elements.You have al-ready seen the setting of'primitive'properties in the example about,the setting of collaborators is done usingthe nested <ref> element.<beans>...<bean id="exampleDataAccessObject"class="example.ExampleDataAccessObject"><!-- results in a setDataSource(BasicDataSource) call --><property name="dataSource"><ref bean="myDataSource"/></property></bean></beans>As you can see below,we're using the Commons DBCP datasource fromthe previous example here as a collab-orator and we're specifying if using a <ref bean> element.References exist in three types that specify whetheror not to search the collaborator in the same XML file or in some other XML file (multiple XML files is cov-ered further along): bean:tries to find the collaborator in either the same XML file or in some other XML file that has also beenspecified local:tries to find the collaborator in the current XML file.This attribute is an XML IDREF so it has to exist,otherwise validation will fail external:explicitly states to find the bean in another XML file and does not search in the current XML fileThere's a couple of possibilities for specifying more complex properties such as lists,properties object andmaps.The following examples show this behavior:<beans>...<bean id="moreComplexObject"class="example.ComplexObject"><!-- results in a setPeople(java.util.Properties) call --><property name="people"><props><prop key="HaaryPotter">The magic property</prop><prop key="JerrySeinfeld">The funny property</prop></props></property><!-- results in a setSomeList(java.util.List) call --><property name="someList"><list><value>a list element followed by a reference</value><ref bean="myDataSource"/></list></property><!-- results in a setSomeMap(java.util.Map) call --><property name="someMap"><map><entry key="yup an entry"><value>just some string</value></entry><entry key="yup a ref"><ref bean="myDataSource</ref></entry>Beans and the ApplicationContextSpring Framework 1.0 19</map></property></bean></beans>Note that the value of a Map entry can also again be a list or another map.3.9.Introduction to the ApplicationContextThe context package is built on top of the beans package which provides basic functionality for managing andmanipulating beans,often in a programmatic way.The ApplicationContext introduces BeanFactory function-ality in a more framework-style approach.Instead of programmatically loading beans using for example theXmlBeanFactory and retrieving them using the getBean() method,with the ApplicationContext you will beable to let the framework you're working in load your beans using for example the ContextLoader.The basis for the context package is the ApplicationContext interface,located in theorg.springframework.context package.First of all it provides all the functionality the BeanFactory also pro-vides.To be able to work in a more framework-oriented way,using layering and hierarchical contexts,the con-text package also provides the following: MessageSource,providing access to messages in,i18n-style Access to resources,like URLs and files Event propagation to beans implementing the ApplicationListener interface Loading of multiple contexts,allowing some of them to be focused and used for example only by the web-layer of an applicationThe ApplicationContext includes all the functionality the bean factory has as well.This means you can definebeans using the XML format as explained in Section 3.8.2,The XmlBeanFactory and Appendix A,Spring'sbeans.dtd and retrieve them using their name or id.Also,you will be able to use all of the other features ex-plained in this chapter,such as autowring,setter-based or constructor-based depenency injection,dependencychecking,lifecycle interfaces,etcetera.All other features the ApplicationContext includes are described below,as well as the ways to access an ApplicationContext,load beans into an ApplicationContext and the ways tocustomize existing ApplicationContexts using special beans defined in them.3.10.Added functionality of the ApplicationContextAs already stated in the previous section,the ApplicationContext has a couple of features that distinguish itfromthe BeanFactory.Let us review themone-by-one.3.10.1.Using the MessageSourceThe ApplicationContext interface extends an interface called MessageSource,and therefore provides messaging(i18n) functionality.Together with the NestingMessageSource,capable of hierarchical message resolving,these are the basic interfaces Spring provides to do message resolving.Let's quickly review the methods de-fined there: String getMessage (String code,Object[] args,String default,Locale loc):the basic methodto retrieve a message from the MessageSource.When no message could be found for the locale specified,the default message is used.Any arguments passed in are used as replacement values,using the Message-Format functionality provided by the JDKBeans and the ApplicationContextSpring Framework 1.0 20 String getMessage (String code,Object[] args,Locale loc):basically the same as the one abovewith one difference:the fact that no default message can be specified results in a NoSuchMessageExceptionbeing thrown if the message could not be found String getMessage(MessageSourceResolvable resolvable,Locale locale):all properties used in themethods above are also wrapped in a class - the MessageSourceResolvable,which you can use in thismethodWhen an ApplicationContext gets loaded,it automatically searches for a MessageSource bean defined in thecontext.The bean has to have the name messageSource.If such a bean is found,all calls to the methodsdesribed above will be delegated to the message source that was found.If no message source was found,theApplicationContext inspects to see if it has a parent containing a similar bean,with a similar name.If so,it usesthat bean as the MessageSource.If it can't find any source for messages,an empty StaticMessageSource willbe instantiated in order to be able to accept calls to the methods defined above.Spring provides two MessageSource implementation at the moment.These are the ResourceBundleMessage-Source and the StaticMessageSource.Both implement NestingMessageSource in order to be able to donested messaging.The StaticMessageSource is hardly ever used and provides programmatic ways to add mes-sages to the source.The ResourceBundleMessageSource is more interesting and is the one we will provides anexample for:<beans><bean id="messageSource"class="org.springframework.context.support.ResourceBundleMessageSource"><property name="baseNames"><list><value>format</value><value>exceptions</value><value>windows</value></list></property></bean></beans>This assumes you have three resource bundles defined on your classpath called format,exceptions and win-dows.Using the JDK standard way of resolving messages through ResourceBundles,any request to resolve amessage will be handled.3.10.2.Propagating eventsEventhandling in the ApplicationContext is provided through the ApplicationEvent class and Application-Listener interface.When implementing the ApplicationListener in one of your beans,everytime an Appli-cationEvent gets published to the ApplicationContext,your bean will be notified,based on the standard Ob-server design pattern implemented by the java.util package.Spring provides three standard events:Table 3.4.Built-in EventsEventExplanationContextRefreshedEventEvent published when the ApplicationContext is initialized or refreshed.Ini-tialized here means that all beans are loaded,singletons are pre-instantiatedand the ApplicationContext is ready for useContextClosedEventEvent published when the ApplicationContext is closed,using the close()method on the ApplicationContext.Closed here means that are singletons aredestroyedBeans and the ApplicationContextSpring Framework 1.0 21EventExplanationRequestHandledEventA web-specific event telling all beans that a HTTP request has been serviced(so it'll be published after the request has been finished).Note that this eventis only applicable for web applications using Spring's DispatcherServletImplementing custom events can be done as well.All you need to do is call the publishEvent() method on theApplicationContext and you're done.Let's have a look at an example.First,the ApplicationContext:<bean id="emailer"class="example.EmailBean"><property name="blackList"><list><value>black@list.org</value><value>white@list.org</value><value>john@doe.org</value></list></property></bean><bean id="blackListListener"class="example.BlackListNotifier"><property name="notificationAddress"><value>spam@list.org</value></property></bean>and then,the actual beans:public class EmailBean implements ApplicationContextAware {/** the blacklist,setter ommitted for brevity */private List blackList;public void setApplicationContext(ApplicationContext ctx) {this.ctx = ctx;}public void sendEmail(String address,String text) {if (blackList.contains(address)) {BlackListEvent evt = new BlackListEvent(address,text);ctx.publishEvent(evt);return;}//send email}}public class BlackListNotifier implement ApplicationListener {/** notification address,setter left our for brevity */private String notificationAddress;public void onApplicationEvent(ApplicationEvent evt) {if (evt instanceof BlackListEvent) {//notify appropriate person}}}Of course,this behavior could be more cleanly implemented maybe,by using AOP features,but just to illus-trate the basic behavior,this should do.3.10.3.Using resources within SpringEmphasis:not sure where to cover this,let's leave it for now (so it's not complete yet).Beans and the ApplicationContextSpring Framework 1.0 22A lot of applications need to access resources.Resources here,might mean files,but also newsfeeds from theInternet or normal webpages.Spring provides a clean and transparent way of accessing resources in a protocolindependent way.The ApplicationContext has a method (getResource(String)) to take care of this.The Resource class defines a couple of methods that are shared across all Resource implementations:Table 3.5.Resource functionalityMethodExplanationgetInputStream()Opens an InputStreamon the resource and returns itexists()Checks if the resource exists,returning false if it doesn'tisOpen()Will return true is multiple streams cannot be opened for this resource.Thiswill be false for some resources,but file-based resources for instance,cannotbe read multiple times concurrentlygetDescription()Returns a description of the resource,often the fully qualified file name or theactual URLA couple of Resource implementations are provided by Spring.They all need a String representing the actuallocation of the resource.Based upon that String,Spring will automatically choose the right Resource imple-mentation for you.When asking an ApplicationContext for a resource first of all Spring will inspect the re-source location you're specifying and look for any prefixes.Depending on the implenentation of the Applica-tionContext more or less Resource implementations are available.Resources can best be configured by usingthe ResourceEditor and for example the XmlBeanFactory.3.11.Extra marker interfaces and lifecycle featuresThe BeanFactory already offers you some methods to control the lifecycle of your beans (like Initializing-Bean or init-method and its counterpart,DisposableBean or destroy-method).The context package buildson top of the BeanFactory so you can use those features in the context package as well.Besides the lifecyclefeatures,the ApplicationContext has one extra marker interface you can add to your beans,the Application-ContextAware interface.This interface will be used to let the bean know about the ApplicationContext is livesin,using the setApplicationContext() method,that takes an ApplicationContext as an argument.3.12.Customization of the ApplicationContextWhere the BeanFactory can be customized programmatically using BeanFactoryPostProcessor,the Applica-tionContext can be customized using special beans,defined in your ApplicationContextBeans and the ApplicationContextSpring Framework 1.0 232See the beans chapter for more informationChapter 4.PropertyEditors,data binding,validationand the BeanWrapper4.1.IntroductionThe big question is whether or not validation should be considered business logic.There are pros and cons forboth answers,and Spring offers a design for validation (and data binding) that does not exclude either one ofthem.Validation should specifically not be tied to the web tier,should be easily localizable and it should bepossible to plug in any validator available.Considering the above,Spring has come up with a Validator inter-face that's both basic and usable in every layer of an application.Data binding is useful for allowing user input to be dynamically bound to the domain model of an application(or whatever objects you use to process user input).Spring provides the so-called DataBinder to do exactlythat.The Validator and the DataBinder make up the validation package,which is primarily used in but notlimited to the MVC framework.The BeanWrapper is a fundamental concept in the Spring Framework and is used in a lot of places.However,you probably will not ever have the need to use the BeanWrapper directly.Because this is reference documen-tation however,we felt that some explanation might be right.We're explaining the BeanWrapper in this chaptersince if you were going to use it at all,you would probably do that when trying to bind data to objects,which isstrongly related to the BeanWrapper.Spring uses PropertyEditors all over the place.The concept of a PropertyEditor is part of the JavaBeans specifi-cation.Just as the BeanWrapper,it's best to explain the use of PropertyEditors in this chapter as well,since it'sclosely related to the BeanWrapper and the DataBinder.4.2.Binding data using the DataBinderThe DataBinder builds on top of the BeanWrapper2.4.3.Bean manipulation and the BeanWrapperThe org.springframework.beans package adheres to the JavaBeans standard provided by Sun.A JavaBean issimply a class with a default no-argument constructor,which follows a naming conventions where a propertynamed prop has a setter setProp(...) and a getter getProp().For more information about JavaBeans and thespecification,please refer to Sun's website (java.sun.com/products/javabeans[http://java.sun.com/products/javabeans/]).One quite important concept of the beans package is the BeanWrapper interface and its corresponding imple-mentation (BeanWrapperImpl).As quoted from the JavaDoc,the BeanWrapper offers functionnality to set andget property values (individually or in bulk),get property descriptors and query the readability and writabilityof properties.Also,the BeanWrapper offers support for nested properties,enabling the setting of properties onsubproperties to an unlimited depth.Then,the BeanWrapper support the ability to add standard JavaBeansPropertyChangeListeners and VetoableChangeListeners,without the need for supporting code in the targetclass.Last but not least,the BeanWrapper provides support for the setting of indexed properties.The Bean-Wrapper usually isn't used by application code directly,but by the DataBinder and the BeanFactory.Spring Framework 1.0 24The way the BeanWrapper works is partly indicated by its name:it wraps a bean to perform actions on thatbean,like setting and retrieving properties.4.3.1.Setting and getting basic and nested propertiesSetting and getting properties is done using the setPropertyValue(s) and getPropertyValue(s) methods thatboth come with a couple of overloaded variants.They're all described in more detail in the JavaDoc Springcomes with.What's important to know is that there are a couple of conventions for indicating properties of anobject.A couple of examples:Table 4.1.Examples of propertiesExpressionExplanationnameIndicates the property name corresponding to the methods getName() or isName() and set-Name()account.nameIndicates the nested property name of the property account corresponding e.g.to the meth-ods getAccount().setName() or getAccount().getName()account[2]Indicates the third element of the indexed property account.Indexed properties can be oftype array,list or other naturally ordered collectionBelow you'll find some examples of working with the BeanWrapper to get and set properties.Note:this part is not important to you if you're not planning to work with the BeanWrapper directly.If you'rejust using the DataBinder and the BeanFactory and their out-of-the-box implementation,don't mind readingthis and go on with reading about PropertyEditors.Consider the following two classes:public class Company {private String name;private Employee managingDirector;public String getName() {return this.name;}public void setName(String name) {this.name = name;}public Employee getManagingDirector() {return this.managingDirector;}public void setManagingDirector(Employee managingDirector) {this.managingDirector = managingDirector;}}public class Employee {private float salary;public float getSalary() {return salary;}public void setSalary(float salary) {this.salary = salary;}}PropertyEditors,data binding,validation and the BeanWrap-Spring Framework 1.0 25The following code snippets show some examples of how to retrieve and manipulate some of the properties ofinstantiated:Companies and EmployeesCompany c = new Company();BeanWrapper bwComp = BeanWrapperImpl(c);//setting the company name...bwComp.setPropertyValue("name","Some Company Inc.");//...can also be done like this:PropertyValue v = new PropertyValue("name","Some Company Inc.");bwComp.setPropertyValue(v);//ok,let's create the director and tie it to the company:Employee jim = new Employee();BeanWrapper bwJim = BeanWrapperImpl(jim);bwJim.setPropertyValue("name","Jim Stravinsky");bwComp.setPropertyValue("managingDirector",jim);//retrieving the salary of the managingDirector through the companyFloat salary = (Float)bwComp.getPropertyValue("managingDirector.salary");4.3.2.Built-in PropertyEditors,converting typesSpring heavily uses the concept of PropertyEditors.Sometimes it might be handy to be able to representproperties in a different way than the object itself.For example,a date can be represented in a human readableway,while we're still able to convert the human readable form back to the original date (or even better:convertany date entered in a human readable form,back to Date objects).This behavior can be achieved by registeringcustom editors,of type java.beans.PropertyEditor.Registering custom editors on a BeanWrapper gives itthe knowledge of how to convert properties to the desired type.Read more about PropertyEditors in theJavaDoc of the java.beans package provided by Sun.A couple of examples where property editing is used in Spring setting properties on beans is done using PropertyEditors.When mentioning java.lang.String as thevalue of a property of some bean you're declaring in XML file,Spring will (if the setter of the correspond-ing property has a Class-parameter) use the ClassEditor to try to resolve the parameter to a Class object parsing HTTP request parameters in Spring's MVC framework is done using all kinds of PropertyEditorsthat you can manually bind in all subclasses of the CommandControllerSpring has a number of built-in PropertyEditors to make life easy.Each of those is listed below and they are alllocated in the org.springframework.beans.propertyeditors package:Table 4.2.Built-in PropertyEditorsClassExplanationClassEditorParses Strings representing classes to actual classes and the otherway around.When a class is not found,an IllegalArgumentExcep-tion is thrownFileEditorCapable of resolving String to File-objectsLocaleEditorCapable of resolving Strings to Locale-objects and vice versa (theString format is [language]_[country]_[variant],which is the samething the toString() method of Locale providesPropertyEditors,data binding,validation and the BeanWrap-Spring Framework 1.0 26ClassExplanationPropertiesEditorCapable of converting Strings (formatted using the format as de-fined in the JavaDOC for the java.lang.Properties class) to Proper-ties-objectsStringArrayPropertyEditorCapable of resolving a comma-delimited list of String to a String-ar-ray and vice versaURLEditorCapable of resolving a String representation of a URL to an actualURL-objectSpring uses the java.beans.PropertyEditorManager to set the search-path for property editors that might beneeded.The search-path also includes sun.bean.editors,which includes PropertyEditors for Font,Color andall the primitive types.When in need of a custom editor in your BeanFactory (i.e.you have some exotic type that you need express asa property in an XML file containing beans),you can use the BeanFactoryPostProcessor infrastructure to dothis.TODOOOODOOD reference provides more info on how to use the BeanFactoryPostProcessor.The fol-lowing piece of code shows the actual processor that registered a customeditor for use with the BeanFactory:public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {beanFactory.registerCustomEditor(Date.class,new CustomDateEditor());}}4.3.3.Other features worth mentioningBesides the features you've seen in the previous sections there a couple of features that might be interesting toyou,though not worth an entire section. determining readability and writability:using the isReadable() and isWritable() methods,you can de-termine whether or not a property is readable or writable retrieving PropertyDescriptors:using getPropertyDescriptor(String) and getPropertyDescriptors()