Spring (1) Detailed description of IOC

Source: Internet
Author: User

IOC is the inverse of control inversion.

In the past, references between objects were called through new. With Spring IOC, we can hand over references between objects to others for management, so that we can hand over control to Spring, so it is called control inversion.

The implementation of Spring IOC uses the design model: simple factory, which evolved from a simple factory. Let's look at how Spring IOC evolved.

Simple factory mode implementation:
Package org; // abstract interface Fruit {public void eat () ;}// implementation class Aclass Apple implements Fruit {public void eat () {System. out. println ("eat apple. ") ;}// Implementation class Bclass Orange implements Fruit {public void eat () {System. out. println ("eat oranges") ;}// Factory class Factory {public static Fruit getInstance (String className) {Fruit f = null; if (className. equals ("apple") {f = new Apple ();} if (className. endsWith ("orange") {f = new Orange ();} return f ;}} public class FactoryDemo02 {public static void main (String args []) {Fruit f = Factory. getInstance ("apple"); f. eat ();}}
Reflection + simple factory, but if the factory class is written like this, there will be a problem. If fruit, such as bananas, needs to be modified in the factory class, this is unreasonable, and the reflection mechanism of java can solve this problem.
Package org1; interface Fruit {public void eat ();} class Apple implements Fruit {public void eat () {System. out. println ("eat Apple. ") ;}} Class Orange implements Fruit {public void eat () {System. out. println ("eat oranges") ;}} class Factory {public static Fruit getInstance (String className) {Fruit f = null; try {f = (Fruit) Class. forName (className ). newInstance ();} catch (Exception e) {e. printStackTrace ();} return f;} public class CopyOfFactoryDemo03 {public static void main (String args []) {Fruit f = Factory. getInstance ("org1.Apple"); f. eat ();}}

Reflection + simple factory + xml configuration file uses the reflection mechanism of java to dynamically instantiate various types. However, this program still has a problem, that is, the main function needs to fill in a complete class name, which is not convenient enough, so you need to add a configuration file to simplify
Package org3; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. util. properties; interface Fruit {public void eat ();} class Apple implements Fruit {public void eat () {System. out. println ("eat apple. ") ;}} Class Orange implements Fruit {public void eat () {System. out. println ("eat oranges") ;}} class Factory {public static Fruit getInstance (String className) {Fruit f = null; try {f = (Fruit) Class. forName (className ). newInstance ();} catch (Exception e) {e. printStackTrace ();} return f;} class PropertiesOperate {private Properties pro = null; private File file = new File ("d:" + File. separator + "fruit. properties "); public PropertiesOperate () {this. pro = new Properties (); if (file. exists () {try {pro. loadFromXML (new FileInputStream (file);} catch (Exception e) {e. printStackTrace () ;}} else {this. save () ;}} private void save () {this. pro. setProperty ("apple", "org3.Apple"); this. pro. setProperty ("orange", "org3.Orange"); try {this. pro. storeToXML (new FileOutputStream (this. file), "Fruit");} catch (Exception e) {e. printStackTrace () ;}} public Properties getProperties () {return this. pro ;}} public class CopyOfFactoryDemo04 {public static void main (String args []) {Properties pro = new PropertiesOperate (). getProperties (); Fruit f = Factory. getInstance (pro. getProperty ("apple"); f. eat ();}}

The final version of Spring IOC solves the problem of adding a configuration file. If you want to add a new fruit class in the future, you must register it in this configuration file. At this time, we can say that the configuration file can control program execution, and now it looks a bit like spring's ioc. Let's take a look at how Spring IOC is implemented.
package test2;public class Person {private String name;private int age;private Grade grade;public String getName() {return name;}public Grade getGrade() {return grade;}public void setGrade(Grade grade) {this.grade = grade;}public void setName(String name) {this.name = name;}public void setAge(int age) {this.age = age;}public int getAge() {return age;}public int getTotleGrade() {return grade.getEnglish()+grade.getMath();}}

package test2;public class Grade {private int math;private int english;public int getMath() {return math;}public void setMath(int math) {this.math = math;}public int getEnglish() {return english;}public void setEnglish(int english) {this.english = english;}}

Bean. xml configuration file (this file only needs to be placed in the test2 package)
 
 
  
// Many beans
  
   
// The first Bean is a Person class. You can take the id name as needed and write the full name of the class.
   
    
// All the attributes in this class are listed below and assigned values. Do you have to assign values? I want to. I just learned, but I don't know.
    
     
Xiaolong
    // The name here is assigned through the set in the program. If you do not believe that you have removed the related set in the program, an error occurs.
   
   
    
     
23
    
   
   
    
// This is a bit special. This grade variable is an object and should be treated differently from the general variable.
    // This directs to a bean named Grade (id = Grade) in this configuration file.
   
  
  
   
// Same as above
   
    
     
99
    
   
   
    
     
59
    
   
  
 

Test class
Package test2; import org. springframework. beans. factory. beanFactory; import org. springframework. beans. factory. xml. xmlBeanFactory; import org. springframework. core. io. classPathResource; import org. springframework. core. io. resource; import test. exampleBean; public class Test {public static void main (String args []) {Resource input = new ClassPathResource ("test2/Bean. xml "); // Bean. xml Path: System. out. println ("resource is:" + input); BeanFactory factory = new XmlBeanFactory (input); // throw input to the factory, this factory will provide you with an instance (I don't know if I can say this) Person person = (Person) factory. getBean ("Person"); // you need something called Person. Well, the factory will go to "Person" to give you Grade = (grade) factory. getBean ("Grade"); System. out. println ("name:" + person. getName (); // person can call the related methods in it, which is equivalent to a new Person System. out. println ("Age:" + person. getAge (); System. out. println ("Mathematical score:" + grade. getMath (); System. out. println ("English score:" + grade. getEnglish (); System. out. println ("mathematics, English total score:" + person. getTotleGrade ());}}

In this case, when you compare the fruit program at the beginning, you will find that the spring configuration file is still a factory, but in the same form, it manages all the classes, the newly created class should be registered in the factory, otherwise it cannot be used by the main program. That is why ioc is an upgraded version of the factory model. As for the writing of configuration files, it is just like accumulation of wood.
------------------------------- By the way, the method for reading the configuration file from Spring is: applicationcontext --- FileSystemXmlApplicationContext --- this method loads the configuration file from the absolute path of the file.
ClassPathXmlApplicationContext --- this method is used to load the configuration file from classpath (suitable for loading relative paths) XmlWebApplicationContext-a method customized for web projects, which is recommended for Web projects.
Beanfactory ---ClassPathResource --- load from the system class path
FileSystemResource --- load from the file system, such as specifying the full path of the configuration file
InputStreamResource --- load from input stream
ServletContextResource --- load from the Servlet context
UrlResource --- load from the specified Url
--------------------------------------------- Difference between BeanFactory and ApplicationContextApplicationContext interface, which is derived from the BeanFactory interface and provides all BeanFactory functions. ApplicationContext works in a more framework-oriented manner and performs context layering and implementation inheritance. The ApplicationContext package also provides the following features:
? MessageSource, providing international Message Access
? Resource access, such as URLs and files
? Event Propagation
? Load multiple (inherited) contexts so that each context focuses on a specific layer, such as the web layer of the application.
The most important thing is that BeanFactory delays loading. When getBean is used, an exception is thrown, and ApplicationContext throws an exception at the beginning of loading. This helps to check whether the dependent attributes are injected; therefore, we usually choose ApplicationContext.





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.