Session EJB Series (vi) Dependency Injection

Source: Internet
Author: User

Before the beginning of this article, let us introduce a concept of "dependency".

What is dependency?

Simply put, the a component needs to invoke the B component, the B component needs to call the C component, and the C component needs to call the D component ... this call is called: Dependency!

In the earliest applications, dependencies are implemented through the New keyword. A component relies on the B component, which is the new a B component that is displayed in the a component. Disadvantages:

1, hard coding, strong coupling, difficult to maintain. A component requires only the methods in the B component, not the creation of the B component!

2, frequent creation of objects, resulting in increased system overhead.

This shortcoming directly spawned the ' factory model '.

In Factory mode, a is no longer responsible for creating B components when a component is dependent on the B component, and the creation of the B component is done by the factory, and a component needs only to be followed by the factory.

From a code perspective, Jndi lookups can be seen as typical factory patterns.

Consider the context as a factory, and Jndi as a product to be produced.

Context ctx=new InitialContext ();

xxx xx= (XXX) ctx.lookup (JNDI);

In fact, Jndi is not a Factory mode! So who in the hell is producing these products? The correct answer is: We usually use XML to configure the object, and actually create these objects is a server, EJB container such a factory, but they are very powerful factory.

after the application server and EJB container have created various objects (such as data source, JMS message purpose, EJB instance), the next step is to give these objects a globally accessible name for outside access. This process is known as:Jndi binding .

When you look up an application server through Jndi, the EJB container is equivalent to the process by which the client wants the components they depend on.

later, the Spring framework proposes the concept of Dependency injection .

When a component relies on the B component, the developer is configured through an XML file or annotation, and the container is responsible for instantiating the B component and injecting the B component into the A component, which is called dependency injection.

it is clear that dependency injection is built on the basis of a factory model and a step forward. With dependency injection, when a component relies on the B component, the A component no longer needs to plant a B component to the factory, but rather the container actively injects the B component into the a component.  

Dependency Injection is more advanced than jndi lookups and is more advantageous for code decoupling.

As for dependency injection, this article mainly explains the following two aspects: resource Dependency, EJB dependency

1. Resource dependent @[email protected]

Such as: A component relies on a data source resource, a JMS message purpose, etc.

2.EJB dependent @[email protected]

For example, a component relies on an EJB.

(i) EJB injection

EJB Injection is provided mainly by the @[email protected] two annotation under the JAVAX.EJB package.

@EJB can be used to modify the member variables of the Bean implementation class or to decorate the bean class setter method. The dependency injection of the EJB container automatically injects the corresponding EJB into the field or setter method.

When using @ejb, you can specify the following properties:

Beaninterface: This property specifies the interface that is implemented by the injected EJB. This property is typically used to differentiate whether the referenced bean is a remote call bean or a local bean

Name: Used to specify the name of the registered key in the Jndi enc of the injected bean, which may differ in different application servers.

Beanname: This property specifies the name of the injected EJB, which is convenient to use. The value is equal to the value specified by the <ejb-name...> element in the @stateless.name @Stateful. Name or Ejb-jar.xml in the injected bean.

Mappedname: Specifies the jndi name of the injected EJB, but because the global Jndi name is related to the application server vendor, setting this property may reduce the portability of the application.

This example shows that the locally invoked EJB is injected into the remote invocation of the EJB, thus indirectly allowing the local EJB to provide services externally.

Local invoke EJB, business interface

@LocalPublic interface Hello{public string Hello (string name);}

Invoking EJBS locally, implementing classes

@Stateless (name= "Hello") public class Hellobean implements Hello{public string Hello (string name) {Return name+ ", now Time:" + New Java.util.Date ();}}

New EJB, Business interface

@RemotePublic interface callhello{string Callhello (String name);}

Next, define the new EJB, which is used to invoke the Hello EJB above. (There is no need for jndi lookups at this time, but by dependency injection)

New EJB, Implementing class

@Stateless (mapped= "Callhello") public class Callhellobean implements callhello{@EJB (beanname= "Hello")//Modify Hello instance variable, The EJB container injects an EJB in the app that represents hello to the Hello instance variable. Private Hello hello; public string Callhello (string name) {Final String str= "Call Hello EJB successfully, return value:"; String Result=hello.hello ("Nihao,zhongguo"); System.out.println (Str+result); Return Str+result;}}

Compile the above 4 Java files, then package them into an EJB jar package and deploy them to the server.

Summary: In this example, the EAO layer of the entire application is the local EJB, and the session bean that applies the business logic layer needs to rely on these EAO ejbs. As a result, these eao are injected into the session bean using dependency injection.

as to what session bean is defined as remote? Or the local? This depends on whether the application needs to provide remote access support to the business logic layer.

  

(ii) Resource injection

The usage is basically the same as @ejb, also because of the member variable or setter method that modifies the bean implementation class.

The following properties can be used when using @resource annotation:

String mappedname: Specifies the resource Jndi app name

String Name: This property specifies the external resource Jdni enc name, which may vary slightly in different application servers

Boolean Shareable: This property specifies whether the resource can be shared

Class Type: The property executes the Java class name for the resource

This example will introduce:

@Stateless (mappedname= "Cmt2") @TransactionManagement (Transactionmanagementtype.container) @TransactionAttribute ( transactionattributetype.required) public class Cmt2bean implements cmt2{@Resource (mappedname= "Java ee") Private  DataSource ds=null; @Resourceprivate sessioncontext sessctx;public void Insert () {try {Connection conn=ds.getconnection (); Statement stmt=conn.createstatement (); int result=stmt.executeupdate ("inset into Tb_user" + "value (NULL, ' New user ', ' Zhaolijing ') "); SYSTEM.OUT.PRINTLN (result); Stmt.close (); Conn.close ();} catch (SQLException e) {e.printstacktrace (); Sessctx.setrollbackonly ();}}}

In the example above, @Resource are annotation that are dependent on injection.

@Resource (mappedname= "Java ee"), tells the EJB container to inject the data source that Jndi is a Java EE into the member variable, so the Bean implementation class does not have to initialize the DS member variable. It can then be used to access the database.

Summary: This article mainly describes the origin of "dependency injection", and explains from two aspects: resource dependency, EJB dependency

1. The previous ' dependency ' could be understood as ' call relationship ', a call B, then a in new B.

2. Later, a "factory model" was introduced, allowing the process of creating B to be delivered to the factory. A just need to be with the factory ' to ' B.

3. Later, a ' container ' was created, and the process of creating B was handed over to the container (an unusually powerful factory). Then give B a name for the global access, this process is called Jndi binding. Then a by looking, you can use B.

4. Later, there was a "dependency injection", The container is responsible for instantiating B and injecting B into a, which is called dependency injection. The advantage of this is that when a uses B, a is no longer required to plant/container B, but the container actively injects B into a.

Dependency Injection is more advanced than jndi lookups and is more advantageous for code decoupling.

Session EJB Series (vi) Dependency Injection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.