Spring Framework, IOC container (transfer)
Spring framework, IOC container (transfer) October 2003
You May Have Heard The Buzz this Summer Around THE
Spring framework. In this article, I'll Try to explain what
Spring Sets Out to Achieve, And How I Believe It Can Help You To Develop J2EE Applications.
In this summer, you can hear a lot of surroundings.
Spring framework. This article, I will explain
The role of Spring and how to help you develop J2EE applications.
YET ANOTHER FRAMEWORK?
Oh, another frame?
You may be thinking /// "Not another framework.///" why shouth you bother to read this article, or download the
SPRING FRAMEWORK, WHEN THEN ARE ALREADY MANY OPEN SOURCE (AND PROPRIETARY) J2EE FRAMEWORKS?
You may be thinking /// "No, another frame ///". In many open source J2EE frames, why you will also read this article or download
Spring framework?
I believe That
Spring is Unique, for Several Reasons:
I believe in Sping's unique, with the following reasons:
* IT Addresses areas that Many Other Popular Frameworks Don't.
Spring Focuses Around Providing a Way to Manage Your Business Objects.
*
Spring address area? It is not available in other frameworks.
Spring only around a point, that is, managing business objects.
*
Spring is Both Comprehensive and Modular.
Spring has a layered architecture, meaning that you can choose to use just about any part of it in isolation, yet its architecture is internally consistent. So you get maximum value from your learning curve. You might choose to use
Spring Only to Simplify Use of JDBC, For Example, or You Might Choose to Use
Spring to manage all your business objects.
*
Spring is very comprehensive and standard.
Spring is a hierarchical architecture, meaning that you can choose to use only part of it without affecting others. Its architecture system is internal compatible. So you will get the maximum value in your learning curve.
For example, you can choose only
Spring's JDBC single application or use
Spring manages your business object.
* It's designed from the ground up to help you write code That's Easy to test.
Spring is an ideal framework for test driven provjects.
*
Spring's design helps you write test code from the surface to simply write.
Spring is an ideal test drive project frame.
Spring is not necessarily one more framework dependency for your project.Spring is potentially a one-stop shop, addressing most infrastructure concerns of typical applications. It also goes places other frameworks do not.
In your project,
Spring does not have to rely on more frameworks.
Spring is equivalent to a one-stop store, engaged in the foundation framework involving typical applications. It does not have to replace any framework.
Although It Has Been An Open Source Project Only Since February 2003,
Spring has a long heritage. The open source project started from infrastructure code published with my book, Expert One-on-One J2EE Design and Development, in late 2002. Expert One-on-One J2EE also laid out the basic architectural thinking behind
Springs.
although
Spring is a open source project starting in February 2003, but it has a long time. This open source project begins
(Published in 2002)
Basic code published, this book also shows
Spring after Spring. However, this architecture is born in 2000, and the self-employment of successful development experience of a series of commercial projects.
Since January 2003,
Spring Has Been Hosted On SourceForge. There Are Now Ten Developers, Of Whom Six Are Highly Active.
Since January 2003,
Spring is built on the SourceForge. There are 10 developers, 6 masters.
Architectural Benefits of
Spring
Spring architecture
Before get down to specifics, let's look at some of the benefits
Spring can Bring to a project:
Let's take a look before we detail
Spring can give a project benefits:
*
Spring Can Effectively Organize Your Middle Tier Objects, Whather OR Not You Choose To Use EJB.
Spring Takes Care of Plumbing this.
*
Spring can effectively organize your intermediate object, whether you choose EJB. If you use struts or other frameworks to connect specific J2EE APIs,
Spring is more concerned about delegate to your pipe?
*
Spring can Eliminate The Proliferation of Singletons Seen ON Many Projects. In My Experience, this is a major problem, reducing testability and object orientation. *
Spring can eliminate a separate project that looks like multiple projects. With my experience, the main problem is to reduce testing ability and object position.
*
Spring can eliminate the need to use a variety of custom properties file formats, by handling configuration in a consistent way throughout applications and projects. Ever wondered what magic property keys or system properties a particular class looks for, and had to read the
Javadoc or Even Source Code? With
Spring You Simply Look At The Class's
JavaBean Properties. The Use of Inversion of Control (Discussed Below) Helps Achieve this Simplification.
*
Spring can eliminate the needs of the specified diverse custom properties files, with the consistent configuration operation run through this application and project. Diverse property health or system properties find you have to read
Javadoc or even source code? However, sping can make you very simply see these classes
JavaBean's properties. Controlled inverted usage (hereinafter described) can help you complete simplification.
*
Spring Can Facilitate Good Programming Practice By Reducing The Cost of Programming To Interfaces, Rather Than Classes, Almost To Zero.
*
Spring can make good programming habits easier to cultivate, using interface instead of Classes to weaken programming cost, minimize.
*
Spring is designed so what appli 帖子 帖子 帖子 帖子 帖子 Most Business Objects in As Few O
Spring Applications Have No Dependency on
Spring.
*
Spring design makes it possible to rely on very little APIs.
Many business objects in Spring applications do not rely on
Spring.
* Applications Built Using
Spring is Very Easy to Unit Test.
* Applying the use of sping makes unit tests very simple.
*
.
*
Spring is a choice using EJB, better than the decisive application architecture. You can choose to use the decisive application architecture. You can choose to extend the business excuse without affecting the call code.
*
Spring Helps You Solve Many Problems Without Using EJB.
Spring can provide an alternative to EJB that's appropriate for many web applications For example, Spring can use AOP to deliver declarative transaction management without using an EJB container;. Even without a JTA implementation, if you only need to work with a single database.
*
Spring can help you solve many problems with no EJB.
Spring provides selective JEB for multiple web applications. For example,
Spring can use AOP to deliver declarative transaction management, without using the EJB container.
If you only need to work on a single database, you don't even need to support JTA.
*
Spring Provides a Consistent Framework for Data Access, WHETHER Using JDBC OR AN O / R MAPPING Product Such as Hibernate.
*
Spring provides a solid data storage framework, whether using JDBC or O / R mapping products like Hibernate.
Spring really can enable you to import the Simplest Possible Solution To Your Problems. And That's Worth a LOT.
Spring is indeed a simple solution for your program. It has considerable value.
What does
Spring do?
What is SPRING do?
Spring Provides a Lot of FunctionAlity, SO I'll Quickly Review Each Major Area in Turn.
Spring has a lot of features, we can quickly browse each of the main ranges.
Mission Statement
mission details
Firstly, Let's Be Clear on
Spring's scope. Although
Spring Covers a Lot of Ground, WE Do Have Clear Vision as to what it will and shouth't address.
First, let us jump out
Spring. Although
Spring covers a lot of levels, we must clearly understand what he doesn't do.
Spring's main aim is to make j2ee easier to use and promote good programing phactice.
Spring's main goal is to make J2EE easier and easy to use, promote good programming habits.
Spring does not reinvent the wheh. Thus you'll Find no logging packages in
Spring, no connection pools, no distributed transaction coordinator. All these things are provided by open source projects (such as Commons Logging, which we use for all our log output, or Commons DBCP), or by your application server. For the same reason We don't provide an o / r mapping layer. There Are Good Solutions To this problem such as hibernate and jdo.
Spring complies with the principle that does not reinvent the wheel. Therefore, you can't find the log management, connect pool, distributed transaction adjustment in Spring. All of these features can be provided by open source items (such as Commons logging, common dbcp),
Or your application server. The same reason, we do not offer O / R mapping layers because there is already a good solution, such as Hibernate and JDO.
Spring does aim to make existing technologies easier to use. For example, although we are not in the business of low-level transaction coordination, we do provide an abstraction layer over JTA or any other transaction strategy.
The main goal of Spring is to make the existing technique easier. For example, although we don't have low-level transaction adjustment services, we provide an extraction layer above JTA or other matters.
Spring does not directly compete with other open source projects unless we feel we can provide something new. For example, like many developers, we have never been happy with Struts, and feel that there's room for improvement in MVC web frameworks. In some areas , Such As ITS Lightweight IOC Container and AOP Framework,
Spring Does HAVE DIRECT Competition, But These area in Which No Solution Has Become Popular.
Spring Was a Pioneer in this area.)
Spring
Spring has no direct and other open source projects to compete unless we think we have new features. For example, like many developers, we have always feel bad for Strus because it puts our box in it. It provides MVC framework. in.
In some places, like lightweight IOC containers and AOP frames,
Spring will have a direct competition with them, but there is no general forming solution in these regions (
Spring is the pioneer of this area)
Spring also benefits from internal consistency. All the developers are singing from the same hymn sheet, the fundamental ideas remaining faithful to those of Expert One-on-One J2EE Design and Development. And we've been able to use some central concepts, such AS Inversion of Control, Across Multiple Areas.
Spring also benefits from regional consistency. Just like all developers sing the same hymn, everyone supports Expert One-ON-One J2EE Design and Development. And we all use some of the main concepts,
Invert control, crossing multiple areas.
Spring is portable between application servers. Of course ensuring portability is always a challenge, but we avoid anything platform-specific or non-standard, and support users on WebLogic, Tomcat, Resin, JBoss, WebSphere and other application servers.Spring be lightweight Used for application servers. Of course, ensuring lightweight ability has always been a challenge, but we avoid detailed or not standard any platform and support WebLogic, Tomcat, Resin, JBoss, WebSphere, and other application servers.
Inversion of Control Container
Inversion of the container
The core of
Spring's design is the org.
Springframework.beans package, Designed for Working with
.
The design of Spring is ORG.
Springframework.beans package, design coordination
JavaBeans work. This package can be used directly by the user, but can be used as a basic service of many other features.
The next higher layer of abstract is the/// "bean factory.///" a
.
The next higher level is /// "bean factory ///", one
Spring Bean Factory is a Factory that can usually manage connect multiple objects and can re-obtain objects based on NAME.
Bean Factories Support Two Modes of Objects:
Bean Factories support two object modes:
* /// "Singleton ///":. In this case, there's one shared instance of the object with a particular name, which will be retrieved on lookup This is the default, and most often used, mode It's ideal for stateless. Service Objects.
* Single-grain mode: Here, there is an object instance with a special envoy name, which will be able to be retrieved. This is a default mode, and it is the most widely used German model. This mode is an ideal stateless service object .
* /// "prototype ///": in this Case, Each Retrieval Will Result in the creation of an independent Object. For example, this could be used to allow each user to have.com.
* /// "Protocile Mode ///": Here, each of the acquisition results in creation of a separate object, for example, which can be used to allow users to use their own objects.
As organ.
springframework.beans.factory.BeanFactory is a simple interface, it can be implemented for a range of underlying storage methods You could easily implement your own, although few users find they need to The most commonly used BeanFactory definitions are:.. because org.
Springframwork.beans.Factory.BeanFactory is a simple interface that can be implemented by potential storage methods? Although few users need, but this can make you easily expand yourself. Some usually used for BeanFactory definitions :
* The xmlbeanfactory. This Parses A Simple, INTUTIVE XML Structure Defining The Classes and Properties of Named Objects. We provide A DTD to make Authoring Easier.
* This is a simple parser. Define the properties of classes and naming objects according to the XML structure. We provide a DTD to make naming simpler.
* ListableBeanFactoryImpl: This Provides The Ability to Parse Bean Definitions In Properties Files, and create beanfactories programmatical.
* ListableBeanFactoryImpl: This provides the ability to parse bean definitions in the properties file, and write to create BeanFactories.
Each Bean Definition Can Be a Pojo (Defined by Class Name and
. JavaBean initialisation properties), or a FactoryBean The FactoryBean interface adds a level of indirection Typically this is used to create proxied objects using AOP or other approaches:. For example, proxies that add declarative transaction management (This is similar to EJB interception in. Concept, But Works Out Much Simpler in Practice.)
The definition of each bean can be a Pojo (definition Class and
JavaBean initialization properties), or a factorybean interface adds an indirect layer. Representing this will be used to create AOP or other channels
Agent object: For example, join a proxy that declares transaction management. (This is a concept similar to EJB listening, but is very simple in practice)
BeanFactories can optionally participate in a hierarchy, /// "inheriting ///" definitions from their ancestors. This enables the sharing of common configuration across a whole application, while individual resources such as controller servlets also have their own independent set of objects.
BeanFactories can be added at a level, according to their original definition. This can pass through the entire application through the shared application, when individual resources, such as the Controller Servlets, also set yourself for a single object .This Motivation for the use of
JavaBeans Is Described in Chapter 4 of Expert One-ON-One J2EE Design and Developments, Which Is Available on The Serverside as a free PDF
http://www.theserverside.com/res ... DjohnsoninterView).
This is to declare
Javabeans usage, in
Chapter 4, Usage in Serverside Free PDF (
http://www.theserverside.com/res ... DjohnsoninterView).
THROUGH ITS BeanFactory Concept,
Spring is an inversion of control container. (I Don't Much Like The Term Container, AS IT Conjures Up Visions of Heavyweight ContaInions) AS EJB Containers. A
Spring Beanfactory Is A Container That Can Be CREATED IN A Single Line of Core, And Requires No Special Deployment Steps.
Through its beanfactory concept,
Spring is an inversion of a control container. (I am very disappearing because it relies on heavyweight containers, such as EJB containers).
Spring BeanFactory is a container that can be created in a row of code and does not require special deployments)
The concept behind Inversion of Control is often expressed in the Hollywood Principle: /// "Do not call me, I'll call you.///" IoC moves the responsibility for making things happen into the framework, and away from application code. Where configuration is concerned this means that while in traditional container architectures such as EJB, a component might call the container to say /// "where's object X, which I need to do my work ///", with IoC the container Figures out what The Component Needs An X Object, and Provides It To It At Runtime. The Container Does This Figuring Out Based On Method Signatures (SUCH AS)
JavaBean Properties) and, Possibly, Configuration Data Such as XML.
Controlling Inversion (IOC) This sensation is often used in Hollywood in principle: /// "Don't call me, I am calling you ///" The responsibility for you /// "is to record the event that enters Framework, and stay away from application code. In the place where the configuration is involved, that is,
Like EJB, a container architecture, a setup can call the container, and say /// "Where can I work Object X //////>, for the IOC container, this setup requires X object, and is running Provide it execution. Container is signature in method (like
The Javabean property made this foundation is made, and as much as possible, configure data, such as XML.
IOC HAS Several Important Benefits. For example:
Controlling several advantages of invert, for example:
* BECAUSE COMPONENTS DON'T NEED To Look Up Collaborators At Runtime, They're Much Simpler To Write and Maintain. In
Spring's Version of IOC, Components Express Their Dependency On On Other Components Via Exposing
JavaBean setter method Would Be a JNDi Lookup, Which Requires The Developer to Write Code.
* Because components do not need to work together in runtime, they can be easily prepared and maintained. On
Spring's IOC version, the component expresses them through
JavaBean's setter method is supported by other components. This is equal to EJB
The request code written by JNDI Lookup and developers.
* For the Same Reasons, Application Code Is Much Easier To Test.
JavaBean Properties Are Simple, Core
Java and easy to test: Just Write a self-contained JUnit Test Method That Creates The Object and sets the Relevant Properties.
* For the same reason, the application code becomes very easy to test.
The JavaBean property is simple. The main program test has also become easy: just written a JUnit test method that contains its own creation object and setting associated properties.
* A good IoC implementation preserves strong typing. If you need to use a generic factory to look up collaborators, you have to cast the results to the desired type. This is not a major problem, but it is inelegant. With IoC you express strongly typed dependencies in your code and the framework is responsible for type casts This means that type mismatches will be raised as errors when the framework configures the application;. you do not have to worry about class cast exceptions in your code.
* A good IOC performs robust input. If you need to find a collaborator with a general Factory, you have to shape the results you need. This is not a major program, but this is not good. For IOC you Need to be in your
The code and frame response are transmitted to the input styling. This means that the input mechanism will might exist when configuring the application; but do not have to worry about the shape.
* Most business objects do not depend on IoC container APIs. This makes it easy to use legacy code, and easy to use objects either inside or outside the IoC container. For example, Spring users often configure the Jakarta Commons DBCP DataSource as a
Spring bean: there's no need to do this. We say what an oc container isn't Invasive: Using it Won't invade Your Code with depency on its apis. ANY
JavaBean Can Become a Component in A
Spring bean factory.
* Many business objects do not rely on IOC. This makes it simplified to use inheritance code, and simple for the internal and external parts of the IOC container. For example,
Spring users typically configure the CommONS DBCP data source as
Spring bean: This doesn't need to write any
The code can be done. We say that IOC container will not affect: Use APIs that will not affect your code. Any
Javabean can become
A component of Spring Bean Factory.
. This last point deserves emphasis IoC is unlike traditional container architectures, such as EJB, in this minimization of dependency of application code on container This means that your business objects can potentially be run in different IoC frameworks -. Or outside any framework - without code .
Finally, it is necessary to emphasize that IOC is different from traditional container architecture, such as: EJB, applying minimal dependehere, which means your business object can potentially run on different IOC frames - or no frame - without Change any code.
In my experience and this ofha
Spring Users, It's Hard To Overemphasize The Benefits That Ioc Brings to Application Code.
most
Spring users' experience, which emphasizes the benefits of IOC to your code.
IoC is not a new concept, although it's only just made prime time in the J2EE community There are alternative IoC containers:.. Notably, Apache Avalon, PicoContainer and HiveMind Avalon has never become particularly popular, although it is powerful and has a long history , AvaLon Is Fairly Heavyweight and Complex, and Seems More Invasive Than Newer IOC Solutions. PicoContainer IS Lightweight and Emphasizes The Expression of Dependencies Through Construction Rather Than
JavaBean Properties. Unlike
Spring, ITS Design Allows The Definition of Only ONE OBJECT OF Each Type (POSSIBLY A LIMITATION RESULTING ITS REJECTION OF ANY METADATA OUTEJAVA CODE). For a Comparison Between
Spring and picocontainer and other oc frameworks, see the article /// "THE
Spring Framework - a lightweight container /// "on the
Spring Website At
Http://www.springframework.org/docs/lightweight_container.html. This page incduDes a link to the picocontainer website.
IOC is not a new concept, but it has just become essential in the J2EE group. There are also IOC containers to choose: NOTABLY, APACHE AVALON, PicoContainer and HiveMind.avalon will not become universal, although it is very powerful
And there is a long history. Avalon is quite heavyweight and complex, and it looks more than the new IOC solution. PicoContainer is a lightweight and emphasizes the passing of constructors better than
Javabean properties. Unlike
Spring,
It involves allowing multiple inputs to define a number of objects (possibly limited to external)
Java Code Collection Results), as comparison
Http://www.springframework.org/docs/lightweight_container.html. This industry is included
PicoContainer site.
Spring BeanFactories are very lightweight. Users have successfully used them inside applets, as well as standalone Swing applications. (They also work fine within an EJB container.) There are no special deployment steps and no detectable startup time. This ability to instantiate a container Almost Instantly in Any Tier of an Application Can Be Valuable.
Spring beanfactories is very lightweight. Users can be used in Applets as a stand-alone Swing application. (They also work well in EJB containers) No deployment steps and save time. This capability
Indicates that a container can make a significant value at any level of the application.
THE
Spring beanfactory concept is buy throughout
Spring, and is a key reason there
Spring is so interfacely consistent.
Spring is Also Unique Among Ioc Containers IN That It Uses Ioc AS A Basic Concept Throughout a ful-featured framework.
Spring beanfactory concept
Spring, and
The key reason for the coordination of the Spring Center.
Spring is also the only framework for completing all the features in the IOC container.
Most importantly for application developers, one or more BeanFactories provide a well-defined layer of business objects. This is analogous to, but much simpler than, a layer of local session beans. Unlike EJBs, the objects in this layer can be interrelated, and THEIR RELATIONSHIPS Managed by The Owning Factory. Having A Well-Defined Layer of Business Objects Is Very Important To a successful architecture. Many app developers are concerned, one or more beanfactories can provide a defined business object layer. This is similar And very simple, one layer of a local Session Beans. Unlike EJBS, the objects inside this layer
Yes, and their relationship is managed by its own Factory. Providing a well-defined business object layer is a very important point of success framework.
A
Spring ApplicationContext Is A Subinterface of BeanFactory, Which Provides Support for:
Spring ApplicationContext is the sub-interface of BeanFactory, which supports the following:
* Message Lookup, Supporting InternationalizationATIONalization
* Message is looking for, support internationalization
* An Eventing Mechanism, Allowing Application Objects to Publish And Optionally Register To Be Notified of Events
* Event mechanism, allow application object release and operation registration to become an event
* Portable File and Resource Access
* Lightweight files and resource storage
In The Following Example, We Use 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 That Needs to be caled on shutdown can be beregs VIA
Spring /// 's /// "deStroy-method ///" Attribute, to Avoid the need for basicDataSource to import Any
Spring interface.
In the following example, we use the BasicDataSource in a DBCP project. This class (like other existing classes) can be simple
Spring bean factory uses and provides
JavaBean configuration. This kind of precision method that needs to be called when ShutDown can pass
Spring /// "DESTROY-METHOD / / / /" attribute is registered, and there is a lot of many need to be implemented for BasicDataSource.
Spring interface.
Code:
Destroy-method = /// "close ///">
com.mysql.jdbc.driver
JDBC: mysql: // localhost: 3306 / MyDBroot
All The Properties of BasicDataSource We e intended in Are Strings, So We Specify THEIR VALUES with THE
ELEMENT.
Spring Uses the Standard
JavaBean PropertyEditor Mechanism to Convert String Repesentations To Other Types if Necessary.
What we are interested in strings, all the properties of BasicDataSource, so we use
The label specifies their value. If necessary,
Spring standards
The JavaBean property editing mechanism comes to convert String to other types.
Now We define the Dao, Which Has a bean review to the datasource. RELATIONSHIPS BETWEEN Beans Are Specified Using To
ELEMENT:
Now, we define this use of a bean as a DataSource's DAO.
Tags to represent the relationship between Beans:
Code:
Class = // "Example.exampleDataAccessObject ///">
The Business Object Has A Reference To The Dao, And An Int Property (ExampleParam):
This business object involves DAO and has an int attribute (ExampleParam):
Code:
Class = /// "eXample.examplebusinessObject ///">
10
Relationships Between Objects Are Normally Set Explicitly in Configuration, AS in this Example. We consider this to be a good thing. Howeever,
Spring also provides what we call /// "autowire ///" support, a la PicoContainer, where it figures out the dependencies between beans The limitation with this -. As with PicoContainer - is that if there are multiple beans of a particular type IT Impossible to Work Out Which Instance A Dependency of That Type Should Be Resolved To. on The Positive Side, UNSATISfied Dependencies Can Be Caught by Factory Is Initialized.
Spring Also Offers An Optional Dependency Check for Explicit Configuration, Which Can Achieve this Goal.
The relationship between these two objects can be very clear in the configuration, as an example. We think this is very good. No matter what,
Spring also provides support for us /// "autowire ///", a LA PicoContainer, it can judge that the two Beans only see the dependency. PicoContainer limits if there are multiple Beans with special types. This type is impossible to completely solve the type of instance can be determined to determine the dependencies. It is worth mentioning that the dependency of the team can be captured when Factory initializes. (Spring also provides a completion of this goal) External configuration)
We Could Use the Autowire Feature As Follows in The Above Example, IF We Didn // 'T Want To Code these Relationships Explicitly:
In the above example, we can use AutoWire to understand if we don't want to encode these external relationships:
Code:
Class = /// "eXample.examplebusinessObject ///"
Autowire = /// "ByType ///">
10
With this usage,
Spring will work out that the dataSource property of exampleBusinessObject should be set to the implementation of DataSource it finds in the present BeanFactory. It's an error if there is none, or more than one, bean of the required type in the present BeanFactory. West Need To Set The ExampleParam Property, AS IT /// 's Not a Reference.
For this usage,
Spring will be able to understand the DataSource properties of ExampleBusinessObject to find DataSource in the parent BeanFactory, and set it. If you don't find or more than one request type bean generate an error. We also need to set an ExampleParam property because it doesn't have a parameter.
Autowire Support and Dependency Checking IS Presently In Cvs and Will Be Available in
Spring 1.0 M2 (Due October 20, 2003). All Other Features Discussed in this Article Are IN The Current 1.0 M1 Release.
AutoWire support and dependence checking is just added to CVS and will be released
Spring 1.0 M2 (10/20, 2003). All other features discuss the current 1.0 m1 release version.
External Qing Relationships from
Java Code Has An Enormous Benefit over Hard Coding It, as it Possible To Change The XML File without Changing a line of
Java Code. For Example, We Could Simply Change The MyDataSource Bean Definition TO Refer to A Different Bean Class To Use An Alternative Connection Pool, OR A Test Data Source. We Could Use
Spring JNDI Location FactoryBean To Get A Single Alternative XML Stanza. Specifically, this description has a great advantage than hard coding, because only the XML file is changed without changing
Java code. For example, we can simply change the MyDataSource Bean definition to provide different bean class with selective connection pools, or a test data source. We use
Spring JNDI Local FactoryBean Gets a data source from the Application Server two separate selective nodes.
Now let /// 's Look at the
Java Code for the Example Business Object. Note That There Are No
Spring dependencies in the code listing below. Unlike an ejb container, a
Spring Beanfactory Is Not Invasive: You Don /// 'S Normally Need To Code Awareness Of It Into Application Objects.
Let us now see a business object
An example of Java code. Note that there is no
Spring's dependence. Unlike EJB containers,
Spring beanfactory does not have to be embedded: you usually don't need to encode in your application object.
Code:
Public Class ExamplebusinessObject IMplements mybusinessObject {
Private ExampleDataAccessObject DAO;
Private int exampleparam;
Public void setDataAccessObject (ExampleDataAccessObject Dao) {
THIS.DAO = DAO;
}
Public void setxampleparam (int exampleparam) {
THIS.ExampleParam = ExampleParam;
}
Public void mybusinessMethod () {
// Do Stuff for Dao
}
}
Note The Property Setters, Which Correspond to The XML References in The Bean Definition Document. Thase Are Invoked By
Spring before the object is used.
Note Property Settings, in the bean definition document, the corresponding XML definition. This will be before the object is used
Spring call.
Such Application Beans Do Not NEED To Depend ON
Spring: they don /// 'T NEED TO IMPLEMENT ANY
Spring interfaces or extend
Spring classes: They Just Need To Observe
JavaBeans Naming Convention. Reusing One Outside of A
Spring application context is easy, for example in a test environment. Just instantiate it with its default constructor, and set its properties manually, via setDataSource () and setExampleParam () calls. So long as you have a no-args constructor, you are Free to Define Properties if You Want to Support Programmatic Construction In a Single Line of Code. This application bean does not need to rely on
They don't need to perform any
Spring interface or inheritance
Spring Classes: They only need to follow
JavaBeans name conversion.
Spring application content is very simple, such as a test environment. However, the example defines a default constructor and configured attributes via setDataSource () and setExampleParam (). As long as you have a constructor without a parameter, if you want to set the other builder to set other properties freely in a single-row code support program.
Note That the
JavaBean properties are not declared on the business interface callers will work with. They are an implementation detail. We could /// "plug in ///" different implementing classes that have different bean properties without affecting connected objects or calling code.
Note that there is no declaration in business excuses
The Javabean property works together. They are executed in detail. We can insert different bean properties to perform Classes, without hard connection objects or calling code.
Of course
Spring XML Bean Factories Have Many More Capabilities Than Described Here, But this Should Give You A Feel for the Basic Approach. AS Well As Simple Properties, And Properties for Which you have a
Javabeans PropertyEditor,
Spring can Automatic or Handle Lists, Maps and
Java.util.properties.
of course,
Spring XML Bean Factories has more capabilities not described here, but this will give you a basic understanding in the basic steps. There is also a simple property, and
The properties of the Javabean property editor,
Spring automatically operates Lists, Maps, and
Java.util.properties.
Bean factoryies and application contexts are usually associated with a scope defined by the j2ee server, such as:
Bean factories and Application Contexts are usually defined by J2EE Server, for example:
* The servlet context. In the
Spring MVC framework, an application context is defined for each web application containing common objects.Spring provides the ability to instantiate such a context through a listener or servlet without dependence on the
Spring MVC Framework, So it can also be used in struts, webwork or other web frameworks.
Servlet context. In
In the Spring MVC framework, an application Context can define each of the Web application that contains base objects.
Spring provides a context without relying on the listener or servlet
The Spring MVC framework has, so it can also be used for Struts, Webwork, or other web frameworks.
* A servlet: Each Controller Servlet in The
Spring MVC Framework Has ITS OWN Application Context, Derived from the root (Application-Wide) Application Context. It Also Easy To Accomplish this with struts or annother MVC Framework.
A servlet:
The Spring MVC frameworks each servlet controller is represented by its unique application CONTEXT. This can also be simply applied to Struts or other MVC frameworks.
* EJB:
.
EJB:
Spring provides a convenient superclass for EJB creators and BeanFactory loaded from an XML document in an EJB JAR file.
..................... ..
This is in line with the J2EE specification to usually avoid using Singleton to Bean Factory.
However, it /// 's trivial to instantiate a BeanFactory programmatically if we wish For example, we could create the bean factory and get a reference to the business object defined above in the following three lines of code.:
In any case, we will exemplify a beanfactory, the following 3 line code, we create a bean factory and a reference to the defined business object.
Code:
INPUTSTREAM IS = getClass (). GetResourceAsStream (/// "myfile.xml ////////");
XMLBeanFactory BF = New XMLBeanFactory (IS);
MybusinessObject Mbo = (MybusinessObject) bf.getBean (/// "examplebusinessObject //////////////////// 's Even Depend on J2EE, AS THE
Spring Ioc Container IS Pure
Java.
This code works outside of an application Server: not even relying on J2EE because
Spring IoC container is pure
Java.
JDBC Abstract and Data Access Exception Hierarchy
JDBC abstract and data storage exception level
Data Access Is Another Area in Which
Spring SHINES.
Data storage is
Another flash point of Spring.
JDBC Offers Fairly Good Abstract from The Underlying Database, But IS A Painful API To Use. Some of The Problems Include:
JDBC provides a good database abstraction, but it needs to use painful API. These questions include:
The need for verbose error handling to ensure that ResultSets, Statements and (most importantly) Connections are closed after use. This means that correct use of JDBC can quickly result in a lot of code. It's also a common source of errors. Connection leaks can Quickly Bring Applications Down Under Load.
Trouble is to need to be shut down in RESULTSETS, Statements, and (most important) Connections must be turned off. This means that the correct use of JDBC gets the result that requires a lot of code. It is also an incorrect source. Connection leaks can immediately let the application DOWN.
. The relatively uninformative SQLException JDBC does not offer an exception hierarchy, but throws SQLException in response to all errors Finding out what actually went wrong -. For example, was the problem a deadlock or invalid SQL -? Involves examining the SQLState and error code. The meaning of these values. Varies Between Databases.
There is no relevant SQLException. JDBC does not provide an exception level, but throws SQLException in the response. Can not find the actual error - for example, program deadlock or wrong SQL? - Include checkable SQLState and error code. This may be An error between the database.
Spring Addresses these Problems in Two Ways:
Spring solves these problems with two methods:
By providing APIs that move tedious and error-prone exception handling out of application code into the framework The framework takes care of all exception handling;.. Application code can concentrate on issuing the appropriate SQL and extracting results by providing APIs that move tedious and error The tendency to exclude to the frame level outside of application code. This framework can take care of all exception operations; application code can centrally publish appropriate SQL and extraction results.
By Providing a meaningful exception hierarchy for your application code to work with in place of sqlexception .when
Spring First Obtains a Connection from A DataSource It Examines The Metadata To Ascertain The Database. It Uses this Knowledge to Map Sqlexceptions to The Correct Exception In Its Own Hierarchy Descended from Org.
Springframework.dao.dataaccessException. Thus your code can work with meaningful exceptions, and NEED NOT WORRY About ProPrietary SqlState Or Error Codes.
Spring's data access Exceptions Are Not JDBC-Specific, SO Your daos Are Not Necessarily Tied to JDBC Because of the Exceptions They May THROW.
For your application code, by providing an exception level that works on SQLException. When
Spring won a connection in DataSource, which will check the metadata of the database. Use the drawing SQLException to the current exception in its own level.
SpringFramework.dao.dataAccessException. Thus, your code can run with meaningful Exceptions, and don't have to worry about any SQLState or error code.
Spring's data storage exception is not a JDBC specification, so your DAOS does not have to rely on JDBC because they can throw an exception.
Spring Provides Two Levels of JDBC API. The First, in The ORG.
springframework.jdbc.core package, uses callbacks to move control - and hence error handling and connection acquisition and release - from application code inside the framework This is a different type of Inversion of Control, but equally valuable to that used for configuration management..
Spring provides the level of 2 JDBC APIs. The first one, in ORG.
Springframework.jdbc.core package, use Callbacks to move control - therefore error operation and connection get release - the application code from Framework. This is a different type of inverted control, however, this is the same as configuration management value .Spring uses a similar callback approach to address several other APIs that involve special steps to acquire and cleanup resources, such as JDO (acquiring and relinquishing a PersistenceManager), transaction management (using JTA) and JNDI.
Spring Classes That Perform Such Callbacks Are Called Templates.
Spring With a similar callback method through several other APIs, this includes special steps to obtain and remove resources, such as JDO (gain, and release a PersistenceManager), transaction management (with JTA) and JNDI.
Spring classes provides several CallBacks call modes.
For Example, THE
Spring JDBCTemplate Object Can Be Used to Perform A SQL Query and Save The Results in A List As Follows:
E.g,
The Spring JDBCTemplate object can be used to provide a SQL Query and save the List result:
Code:
JDBCTemplate Template = New JDBCTEMPLATE (Datasource);
Final List names = new linkedlist ();
Template.Query (/// "select user.name from user ///",
New rowcallbackhandler () {
Public Void ProcessRow (ResultSet RS) throws sqlexception {
Names.Add (rs.getstring (1));
}
});
Note That Application Code with the Callback is Free to Throw Sqlexception:
.
Note that this code does not have a Callback code that can be freely throwing SQLException:
Spring will be Catch any one and throw their own exception. Application developers can choose whether to capture or process exceptions or processes.
The JDBCTemplate Provides Many Methods To Support Different Scenarios Including Prepared Statements and Batch Updates. The
Spring JDBC Abstract Has A Very Low Performance Overhead Beyondard JDBC, Even IN Applications Cases Involving HUGE Result Sets.
JDBCTemplate provides a number of methods to support different situations, including preparation statement and bulk updates.
Spring JDBC Abstract performance is far more than even in the application contains a large number of RESULT STS standard JDBC.
The higher level JDBC abstraction is in the org.springframework.jdbc.object package This is built on the core JDBC callback functionality, but provides an API in which an RDBMS operation -. Whether query, update or stored procedure - is modelled as a
Java Object. This API WAS Partly Inspired by the JDO Query API, Which i Found Intuitive and highly usable.
This more advanced JDBC abstraction is in ORG.
Springframework.jdbc.object package. This is built on the core function JDBC Callback, however, provides a set of RDBMS operations APIs - no matter the query, update, or store program - simulation one
Java Object. This group of API is inspired by JDO Query API, which is very intuitive and useful.
A Query Object to Return User Objects Might Look Like this:
A Query object returns the user object, which is probably:
Code:
Class UserQuery Extends MappingsqlQuery {
Public UserQuery (DataSource Datasource) {
Super (DataSource, /// "SELECT * from Pub_user_address where user_id =? ///");
DeclareParameter (New SqlParameter (Types.Numeric);
COMPILE ();
}
// map a result set row to a
Java Object
Protected Object MapRow (ResultSet RS, INT Rownum) throws sqlexception {
User User = new user ();
User.setid (rs.getlong (/// "user_id /////")));
User.setForeName (rs.getstring (/// "forname /////////////////////////////////////////////////////////////////////////////////////////////>
Return User;
}
Public user finduser (long id) {
// use superclass convenience method method to provide strong type
Return (User) FindObject (ID);
}
}
This Class Can Be Used as Follows (This Class is used in the following):
Code:
User User = UserQuery.Finduser (25);
Such Objects Are Off, Unless The Subclass Does Something Unusual.
This object is often used in DAOS. Their thread is secure, unless subclasses have made unusual things.
Another Important Class in The Org.
Springframework.jdbc.Object package is the storedprocedure class.
Spring enables a stored procedure to be proxied by a
Java class with a single business method. If you like, you can define an interface that the stored procedure implements, meaning that you can free your application code from depending on the use of a stored procedure at all. In org.
SpringFramework.jdbc.Object In other important CLASS is StoredProcedure Class.
Spring enables a storage program to be subject to a single business method
Java Class agent. If you like, you can define the interface executed by a storage program, meaning that you can rely on a store program to release your application code.
THE
Spring Data Access Exception Hierarchy is based on unchecked (Runtime) Exceptions. Having Worked with
Spring on Several Projects I'm more and more convinced That this was the right decision.
Spring data storage exception does not check at runtime. For
Spring a few objects of the object, I think the weight is the result of confirming this is right.
Data access exceptions not usually recoverable. For example, if we can not connect to the database, a particular business object is unlikely to be able to work around the problem. One potential exception is optimistic locking violations, but not all applications use optimistic locking . It's usually bad to be forced to write code to catch fatal exceptions that can not be sensibly handled. Letting them propagate to top-level handlers like the servlet or EJB container is usually more appropriate. All
Spring Data Access Exceptions Aresu Subclasses of DataAccessException, SO if We do choose to catch all
Spring Data Access Excetions, We can Easily Do SO.
Data storage exceptions can not be resuscited. For example, if we do not connect to a database, a special business object is not very working. Potential exception is an optimistic lock violation, but not all applications are optimistic. This is usually Layer is forced to write code catch fat and cannot be obviously operated. Like the servlet or EJB container, let them pass them to the uppermost comparison. All
Spring data storage exception is the subclass of DataAccessException, so if we choose Catch all data storage exception, we can complete it.
Note that if we do want to recover from an unchecked data access exception, we can still do so. We can write code to handle only the recoverable condition. For example, if we consider that only an optimistic locking violation is recoverable, we can write Code in Aspring Dao As Follows:
Note If we want to recover from an unknown data access, we can also. We only have to write code to operate recoverable conditions. For example, if we consider only an optimistic lock is not recovered, we can
Spring Dao prepared the following code:
Code:
Try {
// Do Work
}
Catch (OptimisticLockingFailureException ex) {
// I /// 'm INTERESTED IN THIS
}
IF
Spring Data Access Exceptions WERE CHECKED, We'd Need. Note That We Could Choose to Write this Anyway:
in case
Spring data access exception is checked, we need to write the following code. Note that we can choose this:
Code:
Try {
// Do Work
}
Catch (OptimisticLockingFailureException ex) {
// I /// 'm INTERESTED IN THIS
}
Catch (DataAccessException EX) {
// Fatal; Just Rethrow IT
}
One potential objection to the first example - that the compiler can not enforce handling the potentially recoverable exception - applies also to the second Because we're forced to catch the base exception (DataAccessException), the compiler will not enforce a check for. A Subclass (OptimisticLockingFailureexception). So The Compiler Wouldle, US To Write Code To Handle, But Provide, But Provide, But Provide, But Provide, But Provide, But PROVIDE NO HELP IN Forcing Us To DEAL WITH RECOVEM.
In the first example, there is a potential defect - the compiler cannot force the potential unrecoverable abnormality - the second is the same. Because we force the Catch basic exception (DataAccessException), the compiler cannot be enforced as a subclass (OptimisticLockingFailureexception) Do check it. So the compiler enforces us to write the code to operate the program that cannot recover, but does not provide any help.
Spring's use of unchecked data access exceptions is consistent with that of many - probably most -. Successful persistence frameworks (Indeed, it was partly inspired by JDO.) JDBC is one of the few data access APIs to use checked exceptions TopLink and JDO,. for example, use unchecked exceptions exclusively Gavin King now believes that Hibernate should also have opted for unchecked exceptions.Spring unchecked access exception usage for the most part are consistent. - successful persistence frameworks (indeed, from this part of JDO Inspiration.) JDBC is a minority Apis.toplink and JDO at the Check Exception Data Access, for example, not specific check exceptions. Gavin King Now Hibernate does not check Unchecked Exception.
Spring JDBC CAN Help You in Several Ways:
Spring JDBC can help list a few:
You'll Never Need to Write a Finally Block Again To Use JDBC
Don't write Finally, just like JDBC.
You'll Need To Write Much Less Code Overall
Don't write a lot of big code
You'll Never Need to Dig Through Your Rdbms Documentation To Work Out What Obscure Error Code It Returns for a Bad Column Name. Your Application Won't be Deprondent On Rdbms-Specific Error Handling Code.
You don't have to deliver the relational database documentation can solve the implicit error code returned for an error column name. Your app is not used to rely on the error operator that is developed by the relational database.
.......................
No matter how long-lasting technology, you can make you easily implement DAO mode, and business logic does not rely on any special data access API.
In practice we find that all this amounts to substantial productivity gains and fewer bugs I used to loathe writing JDBC code;. Now I find that I can focus on the SQL I want to execute, rather than the incidentals of JDBC resource management.
In practice, we can find a full substantive productivity quantity and less BUGS. We hate JDBC code; now I can put energy on the SQL I want to do, is much better than additional JDBC resources.
Spring's jdbc abstract can be used Standalone if desired - you are not forced to use the other parts
Spring.
Spring's JDBC abstraction can be used alone - one can use only
Other parts of Spring.