Three methods for Spring dependency injection and three methods for spring dependency Injection

Source: Internet
Author: User

Three methods for Spring dependency injection and three methods for spring dependency Injection

Preparations for Spring dependency injection:

  • Download the jar package containing Spring
  • Decompress the downloaded Spring compressed package file
  • After decompression we will see many jar packages under the libs folder, and we only need the commons-logging-1.0.4.jar, spring-beans-4.2.1.RELEASE.jar, spring-context-4.2.1.RELEASE.jar, spring-context-support-4.2.1.RELEASE.jar, spring-core-4.2.1.RELEASE.jar, spring-expression-4.2.1.RELEASE.jar
  • Create a Dynamic Web Project in Eclipse
  • Import the necessary jar packages to the lib folder under the WEB-INF folder
  • Create the package and class mentioned below under src

After the preparation is complete, we will start the dependency injection Journey:

  • Many people are confused about what dependency injection is and what control inversion is.Dependency Injection(DI) andControl reversal(IOC) is the same concept, they are not home.
  • In general, when a role (caller) needs the assistance of another role (called), in Java, the caller usually needs to create the instance of the caller, that is, a new called object. In Spring, the creation of the called object is not completed by the caller.Control reversalThe creation of the called instance is completed by the Spring container and then injected to the caller.Dependency Injection.
  • Spring uses the configuration file or Annotation (Annotation) to manage Bean implementation classes and dependencies. Spring containers use reflection to create instances based on the configuration file and inject dependencies to them.
  • For example, in ancient productivity and low society, people were self-sufficient. When they went hunting, they needed their own production tools, Arrow (Arrow), to capture their prey. They were completely self-made (new) an arrow (object ). Later, with the development of society, there was a factory that made arrow tools. People did not need to create arrows themselves. Instead, they went to the factory to tell them what they needed, and then the factory would give you the appropriate tools. Then you can sit at home without going to the factory.,The arrow appears when a command is sent. Both the arrow and the arrow are managed by Spring. The dependency between the two is provided by Spring.

Now, let's talk a little bit about it. The following is our question: three methods of dependency injection (setter injection, constructor injection, and interface injection ):

First, create the classes and interfaces that will be used in all three methods.

    Interface: Arrow (Arrow), Person (Person)

    Implementation class: ArrowImpl and PersonImpl

Test class: MainTest

  • Setter Injection

Arrow interface:

package iocdi;public interface Arrow {public String getArrow();}

Person interface:

package iocdi;public interface Person {public void hunt();}

ArrowImpl class:

package iocdi;public class ArrowImpl implements Arrow {@Overridepublic String getArrow() {return "an arrow";}}

PersonImpl class:

Package iocdi; public class PersonImpl implements Person {private Arrow arrow; @ Overridepublic void hunt () {System. out. println ("I get" + arrow. getArrow () + "to hunt. ");} // set injects an Arrow public void setArrow (arrow Arrow) {this. arrow = arrow ;}}

    MainTest class:

Package iocdi; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext;/*** @ author ForeverLover */public class MainTest {public static void main (String [] args) {ApplicationContext ac = new ClassPathXmlApplicationContext ("ApplicationContext. xml "); System. out. println ("----------------- setter injection -----------------"); Person p = ac. getBean ("PersonImpl", PersonImpl. class); p. hunt ();}}

ApplicationContext. where does xml come from? The Spring container helps us to create the Instance Object bean. When the process starts, the Spring container will automatically load the configuration file, parse the bean configured in the configuration file and create an instance of the corresponding class. The caller injects the bean to the caller in the specified Method to Control inversion and dependency injection. The content of ApplicationContext. xml configuration file is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.spring Ingress http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <bean id =" ArrowImpl "class =" iocdi. ArrowImpl "/> <bean id =" PersonImpl "class =" iocdi. PersonImpl "> <! -- Setter injection --> <property name = "arrow" ref = "ArrowImpl"/> </bean> </beans>

After all the work is completed, execute the main method of the test class MainTest. The result is OK on the console:

    

  • Constructor Injection

Setter injection is finished. Now let's talk about constructor injection. The so-called constructor injection is to pass the parameter to this object when instantiating the object. We know that there must be constructor for JavaBean, there is at least one non-argument constructor. In this case, we can continue the following constructor injection. The difference with setter injection is that PersonImpl obtains the ArrowImpl instance method, and the Arrow and Person interfaces remain unchanged, the ArrowImpl class remains unchanged. Let's modify the PersonImpl class and ApplicationContext. xml file:

Modified PersonImpl class:

package iocdi;public class PersonImpl implements Person {private Arrow arrow;public PersonImpl() {}public PersonImpl(Arrow arrow) {this.arrow = arrow;}@Overridepublic void hunt() {System.out.println("I get " + arrow.getArrow() + " to hunt.");}}

The modified ApplicationContext. xml file:

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.spring Ingress http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <bean id =" ArrowImpl "class =" iocdi. ArrowImpl "/> <bean id =" PersonImpl "class =" iocdi. PersonImpl "> <! -- Construct an injection --> <constructor-arg ref = "ArrowImpl"/> </bean> </beans>

Then run the MainTest test class again. The result is still feasible:

    

  • Interface Injection

Unlike setter injection and constructor injection, interface injection does not require bean configuration in xml files, but uses Java reflection to create instances that implement interface classes.

Let's modify the MainTest test class and PersonImpl class:

Modified PersonImpl class:

package iocdi;public class PersonImpl implements Person {private Arrow arrow;@Overridepublic void hunt() {try {Object obj = Class.forName("iocdi.ArrowImpl").newInstance();arrow = (Arrow) obj;System.out.println("I get " + arrow.getArrow() + " to hunt.");} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}}}

Modified MainTest class:

Package iocdi;/*** @ author ForeverLover */public class MainTest {public static void main (String [] args) {try {Object obj = Class. forName ("iocdi. personImpl "). newInstance (); Person p = (Person) obj; System. out. println ("----------------- interface injection -----------------"); p. hunt ();} catch (InstantiationException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace ();} catch (ClassNotFoundException e) {e. printStackTrace ();}}}

Run the test class and obtain the result from the console:

    

  • Lookup Injection

By the way, let's talk about the Lookup method injection. There are several classes required for Lookup injection:

Arrow class

Person abstract class

MainTest test class

Create an Arrow class:

package iocdi;import java.util.Random;public class Arrow {private String arrow;private String[] arrows = {"aaaaArrow", "bbbbArrow", "ccccArrow","ddddArrow","eeeeArrow","ffffArrow","ggggArrow","hhhhArrow","iiiiArrow"};public Arrow() {this.arrow = arrows[new Random().nextInt(9)];}public void getArrow() {System.out.println("I get a " + arrow);}}

Create Person class:

package iocdi;public abstract class Person {public abstract Arrow createArrow();public Arrow getArrow() {return new Arrow();}}

Create a MainTest class:

package iocdi;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * @author ForeverLover */public class MainTest {public static void main(String[] args) {ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");Person p = ac.getBean("Person", Person.class);Arrow arrow1 = p.getArrow();Arrow arrow2 = p.getArrow();System.out.println(arrow1.equals(arrow2));System.out.println("------------I am a dividing line------------");Arrow arrow3 = p.createArrow();Arrow arrow4 = p.createArrow();System.out.println(arrow3.equals(arrow4));}}

Modify the ApplicationContext. xml configuration file:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><bean id="Arrow" class="iocdi.Arrow"/>    <bean id="Person" class="iocdi.Person">        <lookup-method name="createArrow" bean="Arrow" />    </bean></beans>

Finally, let's test it. Check the console:

  

  First, the reason why false is output in front of the separator line is that the reference of the two created objects is different. Although it is printed here, the results of eeeeeearrow and ddddddarrow are indeed different because they are random, even if the results may be the same, the references of the two objects are also different. However, the two objects created under the separator line share the same reference. You may also wonder why the abstract class configured in the configuration file can also be instantiated, and the abstract method createArrow () in the abstract class is not implemented but can be used to create an Arrow instance, this is related to the Spring container. It implements the abstarct class. If createArrow () is not an abstract method, the abstract implementation class will also overwrite this method.

Related Article

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.