锘??xml version="1.0" encoding="utf-8" standalone="yes"?>亚洲一区二区三区免费视频,91亚洲国产成人久久精品网址,亚洲av永久无码精品天堂久久http://m.tkk7.com/SteelHand/category/1172.html<strong>涓婂杽鑻ユ按</strong>zh-cnWed, 28 Feb 2007 07:24:12 GMTWed, 28 Feb 2007 07:24:12 GMT60EJB 3.0 vs Springhttp://m.tkk7.com/SteelHand/archive/2005/07/15/7762.html閾佹墜閾佹墜Fri, 15 Jul 2005 04:23:00 GMThttp://m.tkk7.com/SteelHand/archive/2005/07/15/7762.htmlhttp://m.tkk7.com/SteelHand/comments/7762.htmlhttp://m.tkk7.com/SteelHand/archive/2005/07/15/7762.html#Feedback3http://m.tkk7.com/SteelHand/comments/commentRss/7762.htmlhttp://m.tkk7.com/SteelHand/services/trackbacks/7762.html  OnJava涓婄湅鍒頒竴綃囨枃绔狅紝璐村湪榪欓噷錛屽仛涓婄瑪璁般?/FONT>

Albert Einstein once said, "Everything should be made as simple as possible, but not simpler." 錛堝搱鍝堬紝鐩稿璁哄啀綆鍗曪紝涔熶細(xì)浠や笉鐭ュ灝戞劅鍒板ご鐥涳紝鍖呮嫭鎴戙?IMG height=20 src="http://m.tkk7.com/Emoticons/QQ/09.gif" width=20 border=0>錛?/FONT>Indeed, the pursuit of scientific truth has been all about simplifying a theory's underlying assumptions so that we can deal with the issues that really matter. The same can be said for enterprise software development.

A key to simplifying enterprise software development is to provide an application framework that hides complexities (such as transaction, security, and persistence) away from the developers. A well-designed framework promotes code reuse, enhances developer productivity, and results in better software quality. However, the current EJB 2.1 framework in J2EE 1.4 is widely considered poorly designed and over-complicated錛堝鏉傛槸瀵圭殑錛岃璁″掓湭蹇呭樊銆傦級(jí). Unsatisfied with the EJB 2.1 framework, Java developers have experimented with a variety of other approaches for middleware services delivery. Most noticeably, the following two frameworks have generated a lot of developer interest and positive feedback. They are posed to become the frameworks of choice for future enterprise Java applications.

  • The Spring framework is a popular but non-standard open source framework. It is primarily developed by and controlled by Interface21 Inc. The architecture of the Spring framework is based upon the Dependency Injection (DI) design pattern. Spring can work standalone or with existing application servers and makes heavy use of XML configuration files. 錛堜負(fù)浠涔堝氨璁㏒pringg璧朵笂鏄ュぉ浜?jiǎn)锛熷叾瀹濪I鍦ㄥ緢澶氬湴鏂歸兘鐢ㄥ埌浜?jiǎn)锛屽叾瀹炲Q屽簲璇ユ槸璇碨pring 鐢―I鏉ヨВ鍐矲actory鐨勪緷璧栨ч棶棰橈紝榪欑偣鍗犲緱鍏堟満銆傦級(jí)
  • The EJB 3.0 framework is a standard framework defined by the Java Community Process (JCP) and supported by all major J2EE vendors. Open source and commercial implementations of pre-release EJB 3.0 specifications are already available from JBoss and Oracle. EJB 3.0 makes heavy use of Java annotations.錛?STRONG>瑕佹槸鎶㈡爣鍑嗭紝Jboss鏄劇劧涓嶆槸Oracle鐨勫鎵嬶紝榪欎笉JavaOne涔嬪悗錛孫racle鍦ㄨ繖涓婇潰棰嗗厛浜?jiǎn)銆傝繖涓嬶紝Oracle榪炲悓瀹冪嫭姝ュぉ涓嬬殑DB錛屽姞涓婅繖涔堜竴涓寔涔呭眰涓滆タ錛屽緢鏄簡(jiǎn)寰椼傝繖鏍鳳紝Oralce浠婂悗錛屼細(xì)涓嶄細(xì)褰㈡垚JSF(ADF Faces)+EJB3鐨勬牸灞錛屽湪J2EE涓婃潵閭d箞涓涓護(hù)浜哄悆鎯婂憿錛烮BM甯曚笉鎬曪紵涓嶇煡閬擄紝瀹冨拰BEA鎼炵殑SDO涔熸彁鍒頒簡(jiǎn)JCP錛屼笉榪囦笉鐭ュ墠鏅浣曪紵鍝ぉ錛屾娊鏃墮棿浠旂粏鐪嬬湅銆傦級(jí)

These two frameworks share a common core design philosophy: they both aim to deliver middleware services to loosely coupled plain old Java objects (POJOs). 錛?STRONG>POJO鏄釜濂囨殑鍚嶅瓧錛屽叾涓涓涓狾瀛楁瘝錛屽氨浠や漢濂囨傚懙鍛碉紝璋佽鑰佹爲(wèi)涓嶈兘寮鏂拌姳錛熻繖涓嬭鏄悶鐨勯姘磋疆?huà)箒铦{錛屽氨鏈夊ソ鎴忕湅鍟?/FONT>銆?IMG height=20 src="http://m.tkk7.com/Emoticons/QQ/14.gif" width=20 border=0>錛塗he framework "wires" application services to the POJOs by intercepting the execution context or injecting service objects to the POJO at runtime. The POJOs themselves are not concerned about the "wiring" and have little dependency upon the framework. As a result, developers can focus on the business logic, and unit test their POJOs without the framework. In addition, since POJOs do not need to inherit from framework classes or implement framework interfaces, the developers have a high degree of flexibility to build inheritance structures and construct applications.錛?FONT color=#ff1493>鏈夌偣鍖呭姙濠氬Щ鐨勬劅瑙夛紝瀹規(guī)槗灝辨槸榪欎簺POJO鐨勭埗姣嶃傛繪槸瑕佺瓑鍒版渶鍚庯紝鎵嶇煡閬撳拰鑷繁鏈夊叧緋葷殑涓滆タ鏄皝銆傛槸璋佺殑鎮(zhèn)插搥錛熸病鏈夛紝浣嗘効鐨嗗ぇ嬈㈠枩銆傦級(jí)
鍏跺疄錛岃交閲忔灦鏋勫拰鏁忔嵎鏂規(guī)硶鐨勭伀鐖嗕富瑕佹潵婧愪簬鍑犱釜涓昏鐨勫師鍥狅細(xì)1錛岀▼搴忓憳鑷韓鐨勬渚犱富涔夎咃紝鍛靛懙錛屼篃鍙鑻遍泟涓諱箟銆傛繪兂浠涔堥兘浼?xì)锛岃湄?fù)姝﹀姛澶╀笅絎竴錛屽氨鏄噦寰楁洿澶氱殑璇█錛屼粠闇姹傘佸垎鏋愩佽璁°佹祴璇曞埌閮ㄧ講錛屾棤鎵涓嶉氾紝澶氬鐩婂杽銆傚綋鐒惰繖涔熸槸鐢熷瓨鍘嬪姏鐨勫悗鏋溿?BR>2 SUN鏇劇粡璁炬兂錛孞2EE鏄竴涓噸閲忕殑鍥㈤槦鍗忎綔鐨勫紑鍙戞柟寮忥紝鍙槸澶уぇ鍑轟漢鎰忔枡錛岃繖縐嶆柟寮忚姹傚緢楂樼殑杞歡宸ョ▼姘村鉤錛屽悓鏃舵敮鎾戝畠鐨勫悓鏍瘋閲嶉噺鐨勮繃紼嬫ā鍨嬶紝姣斿RUP浠涔堢殑銆備絾鏄ぇ鍨嬬殑鍒嗗竷寮忓簲鐢ㄦ瘯绔熸槸灝戞暟錛屼腑灝忎紒涓氱殑淇℃伅鍖栧簲鐢ㄦ墠鏄富嫻併傝屼笖錛孧S鐨勮В鍐蟲(chóng)柟妗堬紝浠庤繃紼婱SF鍒幫紝 .Net鍜屽紑鍙戠幆澧僔S錛屾棤涓涓嶅湪鐢熶駭鍔涙柟闈㈠崰寰楀厛鏈恒傝佸ぇ錛佽璁頒綇錛岀敤鎴鋒暟閲忔渶鎵鐨勬墠鏄競(jìng)鍦恒?BR>3 鍑轟簬寮鍙戞垚鏈冭檻錛岃佹澘鎬繪槸甯屾湜宸ョ▼甯堟棤鎵涓嶄細(xì)錛岃繖鏍鋒墠鑳藉噺灝戞垚鏈槢錛燂紒鎵嶄細(xì)鍑虹幇寰堝鎷涜仒騫垮憡涓婅繖鏍峰啓閬撯滅簿閫欰,B,C,D,E銆傘傘傘傦紝宸ヤ綔緇忛獙2騫粹濊柂姘村嵈鍙紑鍒?K銆傝繖鏍風(fēng)殑浜嬪ぉ澶╁彂鐢熴傛槸瑙夊緱鍙瑧鍚楋紵榪樻槸瑙夊緱鎮(zhèn)插搥銆傛槸瑙夊緱浜轟簨閮ㄩ棬鐨勯棶棰橈紝榪樻槸璇ュ叕鍙哥殑鎶鏈鐞嗙潃鏍規(guī)湰灝變笉鎳傘傛垨鑰呭氨鏄佹澘鐨勯棶棰樸備笉錛岃繖鏄競(jìng)鍦虹殑闂銆傚悓涓涓蔣浠訛紝瑙勬ā鍜屽姛鑳藉嚑涔庝竴鏍鳳紝鍦ㄥ浗鍐呭崠涓?0涓囷紝寰堥珮?shù)簡(jiǎn)锛屽湪鑻卞浗鍗村崠鍒?0涓囪嫳闀戙傚懙鍛碉紝榪欏氨鏄競(jìng)鍦恒傚競(jìng)鍦哄氨緇濆姝g‘鍚楋紵鍙槸鎴夸環(huán)澶╁ぉ娑紝鐜板湪姣曚笟鐨勭▼搴忓憳錛岀湅鐫鎴夸環(huán)鎬庣殑涓嶆剚錛烴ND.
hehe, 璺戦?shù)簡(jiǎn)銆傘傘傘傘傘傘傘傘傘傘傘傘傘?BR>

However, while sharing an overall philosophy, the two frameworks use very different approaches to deliver POJO services. While numerous books and articles have been published to compare either Spring or EJB 3.0 to the old EJB 2.1, no serious study has been done to compare Spring to EJB 3.0. In this article, I will examine some key differences behind the Spring and EJB 3.0 frameworks, and discuss their pros and cons. The topics covered in this article also apply to other lesser-known enterprise middleware frameworks, as they all converge on the "loosely coupled POJO" design. I hope this article will help you choose the best framework for your needs.

Vendor Independence

One of the most compelling reasons for developers to choose the Java platform is its vendor independence. EJB 3.0 is an open standard designed for vendor independence. The EJB 3.0 specification is developed and supported by all major open source and commercial vendors in the enterprise Java community. The EJB 3.0 framework insulates developers from application server implementations. For instance, while JBoss's EJB 3.0 implementation is based on Hibernate, and Oracle's is based on TopLink, developers need to learn neither Hibernate- nor TopLink-specific APIs to get their applications running on JBoss and Oracle. Vendor independence differentiates the EJB 3.0 framework from any other POJO middleware frameworks available today.錛?STRONG>鍏跺疄榪欑偣涔熸槸瑙佷粊瑙佹櫤浜?jiǎn)锛屾諱箣璧扮潃鐬с?/FONT>錛?/P>

However, as many EJB 3.0 critics are quick to point out, the EJB 3.0 specification has not yet reached the final release at the time of this writing. It will likely be another one to two years before EJB 3.0 is widely adopted by all major J2EE vendors. But even if your application server does not yet support EJB 3.0 natively, you can still run EJB 3.0 applications in the server by downloading and installing an "embeddable" EJB 3.0 product. For instance, the JBoss embeddable EJB 3.0 product is open source and runs in any J2SE-5.0-compatible environment (i.e., in any Java application server). It is currently under beta testing. Other vendors may also soon release their own embeddable EJB 3.0 products, especially for the "data persistence" part of the specification.錛?FONT color=#ff1493>鎭愭曡繕鏄笉濂藉惂錛熶竴閿呯儵錛熷墠浜涘ぉ鐪媁almart榪佺Щ鍒癑ava5錛岀湡澶熷ぇ鑳嗙殑銆?/EM>錛?/P>

On the other hand, Spring has always been a non-standard technology and will remain that way in the foreseeable future. Although you can use the Spring framework with any application server, Spring applications are locked into both Spring itself and the specific services you choose to integrate in Spring.錛?STRONG>鍏跺疄錛屾爣鍑嗕笉鏍囧噯錛屼笉鏄疛CP璇翠簡(jiǎn)綆楃殑銆傛槸澶у澶氫簡(jiǎn)綆楃殑銆?/FONT>錛?/P>

  • While the Spring framework is an open source project, Spring has a proprietary XML format for configuration files and a proprietary programming interface. Of course, this type of lock-in happens to any non-standard product; it is not specific to Spring. But still, the long-term viability of your Spring application depends on the health of the Spring project itself (or Interface21 Inc., which hires most of Spring's core developers). In addition, if you use any of the Spring-specific services, such as the Spring transaction manager or Spring MVC, you are locked into those APIs as well.
  • Spring applications are not agnostic to back-end service providers, either. For instance, for data persistence services, the Spring framework comes with different DAO and template helper classes for JDBC, Hibernate, iBatis, and JDO. So if you need to switch the persistence service provider (e.g., change from JDBC to Hibernate) for a Spring application, you will need to refactor your application code to use the new helper classes.錛?STRONG>榪欑偣灝辨槸鎴戠殑鏈鐖憋紝Spring瀵硅皝閮藉緢鍙嬪ソ錛屼篃璁鎬篃鍖呮嫭榪欓噷鐨凟JB3銆傦級(jí)

Service Integration

From a very high level, the Spring framework sits above application servers and service libraries. The service integration code (e.g., data access templates and helper classes) resides in the framework and is exposed to the application developers. In contrast, the EJB 3.0 framework is tightly integrated into the application server and the service integration code is encapsulated behind a standard interface.

As a result, EJB 3.0 vendors can aggressively optimize the overall performance and developer experience. For instance, in JBoss's EJB 3.0 implementation, when you persist an Entity Bean POJO using the EntityManager, the underlying Hibernate session transaction is automatically tied to the calling method's JTA transaction, and it commits when the JTA transaction commits. Using a simple @PersistenceContext annotation (see later in this article for an example), you can even tie the EntityManager and its underlying Hibernate transaction to an application transaction in a stateful session bean. The application transaction spans across multiple threads in a session and it is very useful in transactional web applications, such as multi-page shopping carts. The above simple and integrated programming interface is made possible due to the tight integration between the EJB 3.0 framework, Hibernate, and Tomcat inside of JBoss. A similar level of integration is also archived between Oracle's EJB 3.0 framework and its underlying Toplink persistence service.

Another good example of integrated services in EJB 3.0 is clustering support. If you deploy an EJB 3.0 application in a server cluster, all of the fail-over, load-balancing, distributed cache, and state replication services are automatically available to the application.錛堣繖鎭愭曚笉鏄疎JB3鐨勫師鍥犲惂錛燂級(jí) The underlying clustering services are hidden behind the EJB 3.0 programming interface and they are completely transparent to EJB 3.0 developers.

In Spring, it is more difficult to optimize the interaction between the framework and the services. For instance, in order to use Spring's declarative transaction service to manage Hibernate transactions, you have to explicitly configure the Spring TransactionManager and Hibernate SessionFactory objects in the XML configuration file. Spring application developers must explicitly manage transactions that span across several HTTP requests. In addition, there is no simple way to leverage clustering services in a Spring application.

(鍏跺疄錛岄氳繃annotation 鎵╁睍浜?jiǎn)璇箟锛岃孲pring 紜疄鐢ㄥ父瑙勬墜孌點(diǎn)傝繖鐐瑰嚭鍙戠偣閮戒笉涓鏍楓?

Flexibility in Service Assembly

Since the service integration code in Spring is exposed as part of the programming interface, application developers have the flexibility to assemble services as needed. This feature enables you to assemble your own "lightweight" application servers. A common usage of Spring is to glue Tomcat together with Hibernate to support simple database-driven web applications. In this case, Spring itself provides transaction services and Hibernate provides persistence services--this setup creates a mini application server 錛?STRONG>榪欎釜瑙傜偣鍊掓槸鏂伴矞錛?/FONT>in itself.

EJB 3.0 application servers typically do not give you that kind of flexibility in picking and choosing on the services you need. Most of the time, you get a set of prepackaged features, some of which you might not need. However, if the application server features a modular internal design, as JBoss does, you might be able to take it apart and strip out the unnecessary features. In any case, it is not a trivial exercise to customize a full-blown application server.

Of course, if the application scales beyond a single node, you would need to wire in services (such as resource pooling, message queuing, and clustering) from regular application servers. The Spring solution would be just as "heavyweight" as any EJB 3.0 solution, in terms of the overall resource consumption.

錛堝綋鐒?dòng)灱孲Pring 鏈韓灝變笉鏄拡瀵瑰垎甯冨紡鐨勫簲鐢ㄩ渶姹傦紝涔熶笉鏀寔銆傛墍浠ワ紝娌″繀瑕佽繖涔堟瘮銆傚叧閿槸鐪嬮拡瀵歸偅浜涘簲鐢ㄣ傦級(jí)
In Spring, the flexible service assembly also makes it easy to wire mock objects, 錛團(tuán)or Testing錛塱nstead of real service objects, into the application for out-of-the-container unit testing. In EJB 3.0 applications, most components are simple POJOs, and they can be easily tested outside of the container. But for tests that involve container service objects (e.g., the persistence EntityManager), in-container tests are recommended, as they are easier, more robust, and more accurate than the mock objects approach.(褰撶劧錛岃劚涓嶈劚紱誨鍣ㄧ殑嫻嬭瘯鍏跺疄瀵瑰ぇ瀹跺茍涓嶉噸瑕侊紝鍏抽敭鏄綆鍗曪紝蹇燂紒)

XML Versus Annotation

From the application developer's point view, Spring's programming interface is primarily based upon XML configuration files while EJB 3.0 makes extensive use Java annotations. XML files can express complex relationships, but they are also very verbose and less robust. Annotations are simple and concise, but it is hard to express complex or hierarchical structures in annotations.錛?STRONG>鎵浠ラ渶瑕佺畝鍖朣pring 鐨刋ML璇硶錛屽敖綆℃垜宸茬粡瑙夊緱寰堢畝鍗曚簡(jiǎn)銆傛瘮璧稴truts涔嬬被鐨勫凡緇忕畝鍗曚笉灝戜簡(jiǎn)銆傦級(jí)

Spring and EJB 3.0's choices of XML or annotation depend upon the architecture behind the two frameworks: since annotations can only hold a fairly small amount of configuration information, only a pre-integrated framework (i.e., most of plumbing has been done in the framework) can make extensive use of annotations as its configuration option. As we discussed, EJB 3.0 meets this requirement, while Spring, being a generic DI framework, does not.錛堣皝鐭ラ亾錛屼互鍚嶴pring 浼?xì)涓嶄細(xì)涔烝notation涓涓?鎴戣寰楀緢鍙兘浼?xì)銆傦級(jí)

Of course, as both EJB 3.0 and Spring evolve to learn from each other's best features, they both support XML and annotations to some degree. For instance, XML configuration files are available in EJB 3.0 as an optional overriding mechanism to change the default behavior of annotations. Annotations are also available to configure some Spring services.

The best way to learn the differences between the XML and annotation approaches is through examples. In the next several sections, let's examine how Spring and EJB 3.0 provide key services to applications.
 

Declarative Services

Spring and EJB 3.0 wire runtime services (such as transaction, security, logging, messaging, and profiling services) to applications. Since those services are not directly related to the application's business logic, they are not managed by the application itself. Instead, the services are transparently applied by the service container (i.e., Spring or EJB 3.0) to the application at runtime. The developer (or administrator) configures the container and tells it exactly how/when to apply services.錛?STRONG>AOP鐨勫ぉ涓?/FONT>錛?BR>

EJB 3.0 configures declarative services using Java annotations, while Spring uses XML configuration files. In most cases, the EJB 3.0 annotation approach is the simpler and more elegant way for this type of services. Here is an example of applying transaction services to a POJO method in EJB 3.0.


public class Foo {
    
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public bar () {
      // do something ...
    }    
}

You can also declare multiple attributes for a code segment and apply multiple services. This is an example of applying both transaction and security services to a POJO in EJB 3.0.


@SecurityDomain("other")
public class Foo {
    
    @RolesAllowed({"managers"})
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public bar () {
      // do something ...
    }   
}

Using XML to specify code attributes and configure declarative services could lead to verbose and unstable configuration files. Below is an example of XML elements used to apply a very simple Hibernate transaction to the Foo.bar() method in a Spring application.


<!-- Setup the transaction interceptor -->
<bean id="foo" 
  class="org.springframework.transaction
        .interceptor.TransactionProxyFactoryBean">
    
    <property name="target">
        <bean class="Foo"/>
    </property>
    
    <property name="transactionManager">
        <ref bean="transactionManager"/>
    </property>
    
    <property name="transactionAttributeSource">
        <ref bean="attributeSource"/>
    </property>
</bean>

<!-- Setup the transaction manager for Hibernate -->
<bean id="transactionManager" 
  class="org.springframework.orm
         .hibernate.HibernateTransactionManager">
    
    <property name="sessionFactory">
        <!-- you need to setup the sessionFactory bean in 
             yet another XML element -- omitted here -->
        <ref bean="sessionFactory"/>
    </property>
</bean>

<!-- Specify which methods to apply transaction -->
<bean id="transactionAttributeSource"
  class="org.springframework.transaction
         .interceptor.NameMatchTransactionAttributeSource">
  
    <property name="properties">
        <props>
            <prop key="bar">
        </props>
    </property>
</bean>

錛圗JB鐨勬柟寮忕殑紜畝鍗曪紝鍙槸濡傛灉澶嶆潅搴︿笂鍗囷紝鎭愭曚紭鍔夸篃涓嶆庝箞鏄庢樉浜?jiǎn)銆傦級(jí)

The XML complexity would grow geometrically if you added more interceptors (e.g., security interceptors) to the same POJO. Realizing the limitations of XML-only configuration files, Spring supports using Apache Commons metadata to specify transaction attributes in the Java source code. In the latest Spring 1.2, JDK-1.5-style annotations are also supported. 錛堝鍟︼紝涔熻浠婂悗鏄釜鏂瑰悜錛屽涔?fàn)鏄緢閲嶈鐨勫Q?/EM>錛塗o use the transaction metadata, you need to change the above transactionAttributeSource bean to an AttributesTransactionAttributeSource instance and add additional wirings for the metadata interceptors.
錛圫pring鐨勪竴涓棶棰樻槸鍚勭鍚嶇О閮戒笉鑲緝鍐欙紝寮勭殑鑰侀暱銆傚綋鐒?dòng)灱屾剰鎬濇洿鍔犳竻妤氭槑浜?jiǎn)銆傦級(jí)


<bean id="autoproxy"
    class="org.springframework.aop.framework.autoproxy
           .DefaultAdvisorAutoProxyCreator"/>
<bean id="transactionAttributeSource"
    class="org.springframework.transaction.interceptor
           .AttributesTransactionAttributeSource"
    autowire="constructor"/>
<bean id="transactionInterceptor"
    class="org.springframework.transaction.interceptor
           .TransactionInterceptor"
    autowire="byType"/>
<bean id="transactionAdvisor"
    class="org.springframework.transaction.interceptor
           .TransactionAttributeSourceAdvisor"
    autowire="constructor"/>
<bean id="attributes"
    class="org.springframework.metadata.commons
           .CommonsAttributes"/>

The Spring metadata simplifies the transactionAttributeSource element when you have many transactional methods. But it does not solve the fundamental problems with XML configuration files--the verbose and fragile transaction interceptor, transactionManager, and transactionAttributeSource are all still needed.

Dependency Injection


錛堣繖騫村ご鏉炬暎鑰﹀悎榪欎箞嫻佽錛屽氨鍍忕敺濂沖叧緋諱箣闂達(dá)紝涓澶滄儏濂界敓嫻佽浼肩殑銆傛垜浠厛鍓嶈鐨勫濮伙紝鎭愭曚篃鐗囬潰浜?jiǎn)浜涖傚悇縐嶆粙鍛沖拰鍚箟錛屽ぇ瀹惰嚜宸變綋浼?xì)鍚с傦級(jí)

A key benefit of middleware containers is that they enable developers to build loosely coupled applications. The service client only needs to know the service interface. The container instantiates service objects from concrete implementations and make them available to clients. This allows the container to switch between alternative service implementations without changing the interface or the client-side code.

The Dependency Injection pattern is one of best ways to implement loosely coupled applications. It is much easier to use and more elegant than older approaches, such as dependency lookup via JNDI or container callbacks. Using DI, the framework acts as an object factory to build service objects and injects those service objects to application POJOs based on runtime configuration. From the application developer's point of view, the client POJO automatically obtains the correct service object when you need to use it.

Both Spring and EJB 3.0 provide extensive support for the DI pattern. But they also have some profound differences. Spring supports a general-purpose, but complex, DI API based upon XML configuration files; EJB 3.0 supports injecting most common service objects (e.g., EJBs and context objects) and any JNDI objects via simple annotations.

The EJB 3.0 DI annotations are extremely concise and easy to use. The @Resource tag injects most common service objects and JNDI objects. The following example shows how to inject the server's default DataSource object from the JNDI into a field variable in a POJO. DefaultDS is the JNDI name for the DataSource. The myDb variable is automatically assigned the correct value before its first use.
(JNDI浠嶇劧鍙互鐜╋紝鍙笉榪噇ookup涔熺敱瀹瑰櫒浠e姵浜?jiǎn)銆傜簿褰╋紒錛佽繖瀵圭Щ妞嶆洿鍔犳柟渚夸簡(jiǎn))


public class FooDao {

    @Resource (name="DefaultDS")
    DataSource myDb;
    
    // Use myDb to get JDBC connection to the database
}

In addition to direct field variable injection, the @Resource annotation in EJB 3.0 can also be used to inject objects via a setter method. For instance, the following example injects a session context object. The application never explicitly calls the setter method--it is invoked by the container before any other methods are called.


@Resource 
public void setSessionContext (SessionContext ctx) { 
    sessionCtx = ctx; 
} 

For more complex service objects, special injection annotations are defined. For instance, the @EJB annotation is used to inject EJB stubs and the @PersistenceContext annotation is used to inject EntityManager objects, which handle database access for EJB 3.0 entity beans. The following example shows how to inject an EntityManager object into a stateful session bean. The @PersistenceContext annotation's type attribute specifies that the injected EntityManager has an extended transaction context--it does not automatically commit with the JTA transaction manager, and hence it can be used in an application transaction that spans across multiple threads in a session.
錛堣繖閲屾墠鏄疎JB鐨勫叧閿傦級(jí)


@Stateful public class FooBean implements Foo, Serializable { @PersistenceContext( type=PersistenceContextType.EXTENDED ) protected EntityManager em; public Foo getFoo (Integer id) { return (Foo) em.find(Foo.class, id); } }

The EJB 3.0 specification defines server resources that can be injected via annotations. But it does not support user-defined application POJOs to be injected into each other.

In Spring, you first need to define a setter method (or constructor with arguments) for the service object in your POJO. The following example shows that the POJO needs a reference to the Hibernate session factory.


public class FooDao {
    
    HibernateTemplate hibernateTemplate;
    
    public void setHibernateTemplate (HibernateTemplate ht) {
        hibernateTemplate = ht;
    }
    
    // Use hibernateTemplate to access data via Hibernate
    public Foo getFoo (Integer id) {
        return (Foo) hibernateTemplate.load (Foo.class, id);
    }
}

Then, you can specify how the container gets the service object and wire it to the POJO at runtime through a chain of XML elements. The following example shows the XML element that wires a data source to a Hibernate session factory, the session factory to a Hibernate template object, and finally, the template object to the application POJO. Part of the reason for the complexity of the Spring code is the fact that we need to inject the underlying Hibernate plumbing objects manually, where the EJB 3.0 EntityManager is automatically managed and configured by the server. But that just brings us back to the argument that Spring is not as tightly integrated with services as EJB 3.0 is.


<bean id="dataSource" 
  class="org.springframework
         .jndi.JndiObjectFactoryBean">
    <property name="jndiname">
        <value>java:comp/env/jdbc/MyDataSource</value>
    </property>
</bean>

<bean id="sessionFactory" 
  class="org.springframework.orm
         .hibernate.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource"/>
    </property>
</bean>

<bean id="hibernateTemplate" 
  class="org.springframework.orm
         .hibernate.HibernateTemplate">
    <property name="sessionFactory">
        <ref bean="sessionFactory"/>
    </property>    
</bean>

<bean id="fooDao" class="FooDao">
    <property name="hibernateTemplate">
        <ref bean="hibernateTemplate"/>
    </property>
</bean>

<!-- The hibernateTemplate can be injected
        into more DAO objects -->

Although the XML-based Dependency Injection syntax in Spring is complex, it is very powerful. 錛堟鍥犲姝わ紝鎵嶅拰鍏跺畠妗嗘灦鍜岄仐鎭ㄥソ鐨勯泦鎴愶紝榪欐牱錛屾灦鏋勫氨鏈夋洿澶氶夋嫨銆?/FONT>錛?/STRONG>You can inject any POJO, including the ones defined in your applications, to another POJO. If you really want to use Spring's DI capabilities in EJB 3.0 applications, you can inject a Spring bean factory into an EJB via the JNDI. 錛?STRONG>榪欐牱INDI涔熸槸鑰佹爲(wèi)鏂拌姳銆傚綋鐒禞NDI鐨勭敤澶勫ぇ浜?jiǎn)锛孞avaEE涓嶅彲鑳戒涪浜?jiǎn)浠栥?/FONT>錛塈n some EJB 3.0 application servers, the vendor might define extra non-standard APIs to inject arbitrary POJOs. A good example is the JBoss MicroContainer, which is even more generic than Spring, as it handles Aspect-Oriented Programming (AOP) dependencies.

Conclusions

Although Spring and EJB 3.0 both aim to provide enterprise services to loosely coupled POJOs, they use very different approaches to archive this goal. Dependency Injection is a heavily used pattern in both frameworks.

With EJB 3.0, the standards-based approach, wide use of annotations, and tight integration with the application server all result in greater vendor independence and developer productivity. With Spring, the consistent use of dependency injection and the centralized XML configuration file allow developers to construct more flexible applications and work with several application service providers at a time.

錛堝悇鏈夋墍闀褲侲JB榪樻槸閽堝楂樼錛孲pring閽堝浣庣錛屼腑闂翠竴閮ㄥ垎閲嶅悎錛屽ぇ瀹朵袱鍏ㄥ叾緹庛?/EM>

榪欑瘒鏂囩珷鍦∣nJava涓綃囬獋澹幫紝榪樻槸寮婧愮殑鍚屽織浠瘮杈冨闃褲傦級(jí)

Acknowledgments

The author would like to thank Stephen Chambers, Bill Burke, and Andy Oliver for valuable comments.

Resources



閾佹墜 2005-07-15 12:23 鍙戣〃璇勮
]]>
主站蜘蛛池模板: 亚洲AV无码一区二区三区网址| 亚洲国产精品乱码在线观看97| 国产成人免费高清激情明星| 色噜噜亚洲精品中文字幕| 猫咪www免费人成网站| 久久九九全国免费| 久久精品网站免费观看| 亚洲精品亚洲人成在线播放| 在线观看日本免费a∨视频| 亚洲AV成人一区二区三区在线看| 亚洲精品黄色视频在线观看免费资源| 两个人看www免费视频| 美女视频黄a视频全免费| 免费在线观看日韩| 极品色天使在线婷婷天堂亚洲| 国产男女猛烈无遮档免费视频网站 | AV在线亚洲男人的天堂| 国产免费MV大全视频网站| 免费H网站在线观看的| 亚洲国产精品嫩草影院| 亚洲狠狠爱综合影院婷婷| a毛片在线看片免费| 久久99国产亚洲精品观看| 最近最好最新2019中文字幕免费| 久草免费福利资源站| 亚洲欧洲春色校园另类小说| 好吊妞998视频免费观看在线| 国产亚洲精品a在线观看app| 日韩中文字幕免费视频| 国产区卡一卡二卡三乱码免费| 亚洲综合综合在线| 成人免费一区二区三区| 亚洲国产成人VA在线观看| a级毛片高清免费视频就| 久久亚洲sm情趣捆绑调教| 久久久久国色AV免费观看性色 | 亚洲宅男精品一区在线观看| 免费乱理伦在线播放| 中文字幕免费视频一| 国产99久久亚洲综合精品| 成年女性特黄午夜视频免费看|