Entry instance of IoC in Spring

Source: Internet
Author: User

The modularization of Spring is very strong, and each functional module is independent. We can choose to use it. This chapter begins with Spring's IoC. IoC is a mode in which XML is used to define the object to be generated. Let's take a look at it.

  Data Model

1. As shown in, there are three classes. Human is an interface, Chinese is a subclass, and American is another subclass.


The source code is as follows:

Package cn.com. chengang. spring;
Public interface Human {
Void eat ();
Void walk ();
}

Package cn.com. chengang. spring;
Public class Chinese implements Human {
/* (Non-Javadoc)
* @ See cn.com. chengang. spring. Human # eat ()
*/
Public void eat (){
System. out. println ("Chinese are very fond of eating ");
}

/* (Non-Javadoc)
* @ See cn.com. chengang. spring. Human # walk ()
*/
Public void walk (){
System. out. println ("Chinese traveling like flying ");
}
}

Package cn.com. chengang. spring;
Public class American implements Human {
/* (Non-Javadoc)
* @ See cn.com. chengang. spring. Human # eat ()
*/
Public void eat (){
System. out. println ("Americans mainly use bread ");
}

/* (Non-Javadoc)
* @ See cn.com. chengang. spring. Human # walk ()
*/
Public void walk (){
System. out. println ");
}
}

2. Use the factory mode for the above objects as follows:

Create a Factory class, as shown below. This factory class defines two string constants that identify different races. The getHuman method determines the race to be generated based on the input parameter string.

Package cn.com. chengang. spring;
Public class Factory {
Public final static String CHINESE = "Chinese ";
Public final static String AMERICAN = "American ";

Public Human getHuman (String ethnic ){
If (ethnic. equals (CHINESE ))
Return new Chinese ();
Else if (ethnic. equals (AMERICAN ))
Return new American ();
Else
Throw new IllegalArgumentException ("parameter (Race) error ");
}
}

The following is a test procedure that uses the factory method to get different "Race objects" and execute the corresponding method.

Package cn.com. chengang. spring;
Public class ClientTest {
Public static void main (String [] args ){
Human human = null;
Human = new Factory (). getHuman (Factory. CHINESE );
Human. eat ();
Human. walk ();
Human = new Factory (). getHuman (Factory. AMERICAN );
Human. eat ();
Human. walk ();
}
}

The output of the console is as follows:


3. Use Spring IoC as follows:

Create a bean. xml file in the project root directory

<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE beans PUBLIC "-// SPRING // dtd bean // EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<Beans>
<Bean id = "Chinese" class = "cn.com. chengang. spring. Chinese"/>
<Bean id = "American" class = "cn.com. chengang. spring. American"/>
</Beans>

The position of bean. xml is as follows. Be careful not to take it as the lib directory. It is under the myspring directory.


Modify the ClientTest program as follows:

Package cn.com. chengang. spring;
Import org. springframework. context. ApplicationContext;
Import org. springframework. context. support. FileSystemXmlApplicationContext;
Public class ClientTest {
Public final static String CHINESE = "Chinese ";
Public final static String AMERICAN = "American ";

Public static void main (String [] args ){
// Human human = null;
// Human = new Factory (). getHuman (Factory. CHINESE );
// Human. eat ();
// Human. walk ();
// Human = new Factory (). getHuman (Factory. AMERICAN );
// Human. eat ();
// Human. walk ();

ApplicationContext ctx = new FileSystemXmlApplicationContext ("bean. xml ");
Human human = null;
Human = (Human) ctx. getBean (CHINESE );
Human. eat ();
Human. walk ();
Human = (Human) ctx. getBean (AMERICAN );
Human. eat ();
Human. walk ();
}
}

From this program, we can see that ctx is equivalent to the original Factory, and the original Factory can be deleted. Then, the two constants in the Factory are moved to the ClientTest class, and the entire program structure is basically the same.

Let's look back at this sentence in the original bean. xml file:

<Bean id = "Chinese" class = "cn.com. chengang. spring. Chinese"/>

Id is the parameter value of ctx. getBean, a string. Class is a class (package name + class name ). Then the Chinese object obtained in the ClientTest class is such a sentence.

Human = (Human) ctx. getBean (CHINESE );

Because the getBean method returns the Object type, you must add a type conversion before.

   Summary

(1) Some people may say that IoC does not play the same role as the factory model. It seems a little more troublesome to use IoC.

For example, if your requirements change, modify the Chinese class. In the previous Factory mode, you must change the methods of the Factory class and re-compile the deployment. IoC only needs to change the class attribute. Since IoC uses the Java reflection mechanism, these objects are dynamically generated, in this case, we can hot dial the Chinese object (you do not have to stop the original program and re-compile the deployment)

(2) Some people may say that IoC is so good, so I use the IoC method to generate all the objects in the system.

Note that the flexibility of IoC comes at a cost: difficult setup steps, inintuitive object generation methods, and slower reflection than normal object generation. Therefore, IoC should be used to check whether it is necessary. In my opinion, the general method of judgment is that IoC can be used in all the places where the factory model is used.

(3) there are some changes in the above IoC method. For example, bean. xml does not have to be stored in the project directory or elsewhere, such as the cn.com. chengang. spring package. However, it must be changed as follows:

New FileSystemXmlApplicationContext ("src/cn/com/chengang/spring/bean. xml ");

In addition, bean. xml can be changed to another name. In this way, we can set different bean. xml in different categories in the system.

(4) Low intrusion to IoC.

What is low intrusion? If you have used Struts or EJB, you will find that you must inherit some interfaces or classes before you can use their framework for development. In this way, the system is bound to Struts and EJB, which has a negative impact on system portability. If the Code rarely involves the code of a framework, this framework can be called a low-invasive framework.

Spring is very invasive. Humen. java, Chinese. java and other classes do not have to inherit any interfaces or classes. However, there are still some Spring shadows in ClientTest: FileSystemXmlApplicationContext and ctx. getBean.
At present, low intrusion seems to be one of the criteria for determining the technical implementation of a framework.

(5) bean. xml usage

Bean. xml is widely used, and its content is quite rich. Suppose there is a humenName attribute (name) in the Chinese class, then the original bean. xml is modified as follows. When a Chinese object is generated later, the value of "Chen Gang" is automatically set to Chi

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.