== Spring Learning> IOC [Inversion of Control]

I. Overview

Spring's three core ideas: IoC (Inversion of Control), DI (dependency injection), AOP (Aspect Oriented Programming). This talk focuses asked about the inversion of control.

What Inversion of Control: Spring facilitates loosely coupled by means of a called inversion (IoC) control technique. When you apply IoC, an object dependent on other objects will be passed in through a passive, rather than the object itself to create or find the dependent objects. You can think of IoC and JNDI opposite - look for a dependency from the container is not an object, but the object is initialized when the container objects ranging request will depend on the initiative passed to it.

Popular speaking, the right to control the external container by the code, the control of the transfer, the so-called inversion. In other words, we are the new normal, a new object, you can call the object. With the inversion of control is not required, to the container to manage, we only need to complete the entity class to such a process container through a number of configurations. This reduces the amount of code complexity and simplify coupling development.

Second, oriented programming interface

In an object-oriented system, the various functions of the system is composed of many different objects done in collaboration. In this case, each object inside is how to achieve their own, in terms of system designers is not so important; and collaborative relationship between various objects is a key system design. Small to communication between different classes, as large as the interaction between the modules in the beginning of system design is an important consideration, which is the main tasks of system design. Oriented programming interface refers to the programming in accordance with this idea.

Oriented programming interface specific to a certain interface for the caller, we do not care which implementation of the interface is implemented by the class, nor care about is how to achieve specific, you simply provide the interfaces to the caller it.

Third, Coding IoC

Here, we use IoC idea to implement a simple interface-oriented programming.

First define two interfaces IAccountService and IOrderService, as follows:

public interface IAccountService {

  int insertAccount(String msg);

}
IAccountService Interface
public interface IOrderService {

  void insert(String msg);

}
IOrderService Interface

Then, these two defined class that implements the interface

public class AccountBigServiceImpl implements IAccountService {

  @Override
  public int insertAccount(String msg) {

    System.out.println("===== AccountBigServiceImpl ====" + msg);

    return 0;
  }
}
AccountBigServiceImpl
public class AccountSamllServiceImpl implements IAccountService {

  @Override
  public int insertAccount(String msg) {

    System.out.println("smallService");

    return 0;
  }
}
AccountSamllServiceImpl
public class OrderServiceImpl implements IOrderService {

  @Override
  public void insert(String msg) {

    System.out.println("===== OrderServiceImpl ====" + msg);
  }
}
OrderServiceImpl

We normally use the following code to call these two interfaces

public class Controller {
  public static void main(String[] args) {
    IAccountService accountService = new AccountBigServiceImpl();
    accountService.insertAccount("Hello!!");

    IOrderService orderService = new OrderServiceImpl();
    orderService.insert("World!!");
  }
}

We direct the new IAccountService and IOrderService two subclasses Controller interface in this class: AccountBigServiceImpl and OrderServiceImpl. This idea contrary to the programming interface for the above mentioned, I only want to deal with business logic Controller in this class, but also concerned about who IAccountService and IOrderService two interfaces specific category that the above is to use this class to implement AccountBigServiceImpl Interface IAccountService, if I want to use this AccountSamllServiceImpl implementation class to implement this interface, then I have to modify the code of the Controller, apparently doing maintenance cost is too high, but also very easy to make mistakes, then we can think of other Method.

First, we use a configuration file to define the interface of these two points of the implementation class

IAccountService=com.jack.course.spring.factory.impl.AccountBigServiceImpl
IOrderService=com.jack.course.spring.factory.impl.OrderServiceImpl
conf.properties

Then, we'll define a class factory

public  class the ServiceFactory { 

  Private  static  Final String CONF_FILE_NAME = "Factory / the conf.properties" ; 

  Private  static the Properties prop; 

  Private  static the Map <String, Object> beanContainer; 

  / ** 
   * static code block will only be loaded once program execution 
   * / 
  static { 

    the try { 
      beanContainer = Maps.newHashMap ();
       // 1. from the configuration file to find out the relationship 
      prop = new new the Properties (); 
      prop.load (. the ServiceFactory class .getClassLoader () the getResourceAsStream (CONF_FILE_NAME).); 
    }catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }

  public static <T> T getService(Class<T> clazz){

    if (beanContainer.containsKey(clazz.getSimpleName())){
      return (T) beanContainer.get(clazz.getSimpleName());
    }

    try {
      //2.根据关系,将具体的实现类返回
      Object obj = instanceObj(clazz);
      beanContainer.put(clazz.getSimpleName(),obj);
      return (T) obj;
    } catch (Exception e) {
      throw new IllegalArgumentException(e);
    }
  }

  private static <T> Object instanceObj(Class<T> clazz) throws Exception {
    String className = prop.getProperty(clazz.getSimpleName());
    Class<?> instance = Class.forName(className);
    return instance.newInstance();
  }
}

Note: The above code does two optimization. First, the operation reads the configuration file to separate out into the static block of code, read only once will not be repeated. Second, the definition of the object class is instantiated as a bean Map storage container, if the container is instantiated objects already exist can be directly returned, not reproduced by the instanceObj () method to instantiate an object, and by two at optimization can greatly improve performance.

This function is implemented factory class: interface implementation class obtained by reading a configuration file conf.properties, and then reflected by the object to generate a pass Controller, so Controller class which can not care who interface implementation class, how realize they do not care.

That so we can achieve the Controller

public class Controller {
  public static void main(String[] args) {

    IAccountService accountService = ServiceFactory.getService(IAccountService.class);
    accountService.insertAccount("Hello!");

    IOrderService orderService1 = ServiceFactory.getService(IOrderService.class);
    IOrderService orderService2 = ServiceFactory.getService(IOrderService.class);
    orderService1.insert("One");
    orderService2.insert("Two");
  }
}

Thus, if we want to change to achieve that kind of thing, only need to modify the configuration file on the line, do not modify the code.

Results are as follows:

Above, we will implement the interface-oriented programming via IoC ideas. However, we realize this is completely no problem?

We slightly modified AccountBigServiceImpl implementation class, an increase constructor parameter to override the default constructor

public class AccountBigServiceImpl implements IAccountService {

  private AccountBigServiceImpl(String msg) {
    System.out.println(msg);
  }

  @Override
  public int insertAccount(String msg) {

    System.out.println("===== AccountBigServiceImpl ====" + msg);

    return 0;
  }
}

And then perform Controller, will be the error. The reason is because when we use newInstance instantiate an object is the default constructor with no arguments.

So, we modify the factory class, you can implement this function. However, you may also find that there are other problems slowly, then we are not going to achieve it all yourself, we can directly use the Spring Framework can be. We can think of the Spring Framework and unexpected features gave realized, we just used directly on it.

The use of XML file to configure IoC

 

Fifth, use the comment + XML file to configure IoC

 

Sixth, use a full annotation configuration IoC

 

Guess you like

Origin www.cnblogs.com/L-Test/p/11593641.html