IOC is usually what we call control reversal, which is also the focus of Java and is often asked during interviews.
Inversion of Control (IoC in English abbreviation) gives the right to create objects to the framework, which is an important feature of the framework and is not a special term for object-oriented programming. It includes Dependency Injection (DI) and Dependency Lookup.
IOC changes the way the program acquires objects, from the beginning of new object to the creation and injection of a third-party framework. Third-party frameworks generally specify which implementation is injected through configuration, thereby reducing the coupling of source code.
What is the biggest benefit of IOC?
Because object generation is defined in XML, it will become very simple when we need to change to an implementation subclass (usually such objects are realistic in some kind of interface), just modify the XML, so that we can even implement hot plugging of objects (a bit like USB interface and SCIS hard disk).
IOC can be divided into dependency injection (DI) and dependency search according to the implementation method.
DI is the main technical approach to control inversion, divided into setter injection and constructor injection
Setter injection
After instantiating the bean by calling the parameterless constructor or static parameterless factory method, the bean's setter method is called to realize setter injection.
public class JDBCDataSource(){private String driver;public void setDriver(String driver){Class.forName(driver);this.driver=driver;}}...............Next, implement setter injection configuration xml file
<bean id="dataSource"> <property name="driver" value="oracle.jdbc.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/> <property name="user" value="andreny"/> <property name="password" value="root"/> </bean>
Constructor injection
This is achieved by calling a constructor with parameters. When the container is instantiated, the corresponding constructor will be executed according to the parameter type.
public class OracleUserDao implements UserDao{private JDBCDataSource dataSource;public OracleUserDao(JDBCDataSource dataSource){this.dataSource=dataSource;}}................Specify injection by construct parameter index
<bean id="dataSource"> <proerty name="driver" value="oracle.jdbc.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/> <property name="user" value="andreny"/> <property name="password" value="root"/></bean><bean id="userDao"> <construtor-argindex="0" ref="dataSource"/></bean>
Summarize
The above is all about Spring's IOC code analysis, I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
Detailed explanation of spring's IoC and DI
Detailed introduction to Spring's Ioc simulation implementation
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!