The Spring IoC uses a detailed

Source: Internet
Author: User

In spring, the Dependency injection (DI) pattern implements the inversion of control (IoC) principle. Let's use an example to help understand dependency injection. Let's start with the Java version of the example, and then add spring functionality on top of that. In the case of example, it is quite simple. the Quizmater interface exposes the Popquestion () method. To keep it simple,quizmaster will only generate one problem.

?
123456789 /** * QuizMaster.java */packagecom.vaannila; public interface QuizMaster {     publicString popQuestion();}

The Strutsquizmaster and Springquizmaster classes implement quizmaster interfaces, each generating struts and spring-related issues.

?
12345678910111213 /** * StrutsQuizMaster.java */package com.vaannila;public class StrutsQuizMaster implements QuizMaster {    @Override    public String popQuestion() {        return "Are you new to Struts?";    }}

?
12345678910111213 /** * SpringQuizMaster.java */package com.vaannila;public class SpringQuizMaster implements QuizMaster {    @Override    public String popQuestion() {        return "Are you new to Spring?";    }}

There is a Quizmasterservice class that displays the problem to the user. The Quizmasterservice class is associated with the Quizmaster interface.

?
12345678910111213 /** * QuizMasterService.java */package com.vaannila;public class QuizMasterService {    private QuizMaster quizMaster = new SpringQuizMaster();    public void askQuestion(){        System.out.println(quizMaster.popQuestion());    }}

Finally, create the Quizprogram class to manage the quiz.

?
12345678910111213 /** * QuizProgram.java */package com.vaannila;public class QuizProgram {    public static void main(String[] args) {        QuizMasterService quizMasterService = new QuizMasterService();        quizMasterService.askQuestion();    }}

It looks fairly simple, we created an instance of the Quizmasterservice class, and called the Askquestion () method. When you execute program, the desired "is younew to Spring?" Will print from the console.

Let's look at the class diagram for this example. A green arrow represents a generalization, and a blue arrow indicates an association.

See, this structure is tightly coupled. An instance of Quizmaster is created in the Quizmasterservice class, as shown below.

?
1 privateQuizMaster quizMaster = newSpringQuizMaster();

To test people who are proficient in struts, we need to modify quizmasterservice into this:

?
1 privateQuizMaster quizMaster = newStrutsQuizMaster();

So coupling is very high, which is why dependency injection is used to avoid this coupling. The spring framework provides a very powerful container for managing components. Containers are based on the inversion of Control (IoC) concept and implement dependency injection. These components simply need to select a way to accept the resource, and the container will automatically push the resources for the component.

Let's replace the Quizmasterservice class with a direct way to create a Quizmaster object so that the container can take the job. Replaced hard-coded, allowing the container to inject the required dependencies.

Injection dependency is injected using setter or constructor method. Here's a look at how to use setter to inject.

?
1234567891011121314151617 /** * QuizMasterService.java */package com.vaannila;public class QuizMasterService {    private QuizMaster quizMaster;        public void setQuizMaster(QuizMaster quizMaster) {        this.quizMaster = quizMaster;    }    public void askQuestion(){        System.out.println(quizMaster.popQuestion());    }}

The value of quizmaster is set using the Setquizmaster () method. In the Quizmasterservice class, the Quizmaster object is not instantiated, but still accesses it. This usually throws a NullPointerException exception, but the container already instantiates the object, so it works well.

Once these changes have been made, the class diagram of the example becomes this way.

The diagram has more containers, which help inject dependencies.

The beans configuration in the Beans.xml file:

?
1234567891011121314 <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">    <bean id="springQuizMaster" class="com.vaannila.SpringQuizMaster"></bean>    <bean id="strutsQuizMaster" class="com.vaannila.StrutsQuizMaster"></bean>    <bean id="quizMasterService" class="com.vaannila.QuizMasterService">         <property name="quizMaster">            <ref local="springQuizMaster" />        </property>    </bean></beans>

Define each bean using the bean label. The id attribute of the bean tag is the logical name of the bean, and the class attribute represents the real bean class. The property tag points to the Bean's properties. Using a setter to inject a bean requires the use of a ref tag.

The Springquizmaster reference is injected into the Quizmasterbean. When we execute this example, the console prints "is you new to Spring?".

In order for Quizmaster to ask a struts-related question, only the reference to the ref tag needs to be changed.

?
123456 <bean id="quizMasterService" class="com.vaannila.QuizMasterService">    <property name="quizMaster">        <ref local="strutsQuizMaster" />    </property></bean>

Dependency injection reduces the coupling between components.

To perform this example, the following jar files need to be enlarged classpath.

antlr-runtime-3.0 commons-logging-1.0.4 org.springframework.asm-3.0.0.m3 org.springframework.beans-3.0.0.m3 ORG.SPRINGFRAMEWORK.CONTEXT-3.0.0.M3 org.springframework.context.support-3.0.0.m3 ORG.SPRINGFRAMEWORK.CORE-3.0.0.M3 org.springframework.expression-3.0.0.m3

Details of the Spring IoC use

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.