Spring Framework Learning (2) IOC learning

Source: Internet
Author: User

Content from: IOC understands the three ways spring IOC injects

Coupling, which behaves as a relationship between classes in Java, strongly demonstrates the strong dependence between classes;

Intrusive: The framework's intrusion into the code;

In the traditional Java development has a high degree of coupling and intrusion type. In a project, generally a class to rely on a lot of other classes to do their own operations, we tend to use the new class of objects to invoke his method, so that the two classes of dependency is too strong, change a place, often involve a lot of classes involved in a large number of code. It can be said that in this context, spring came into being, a lightweight framework to solve the complexity of traditional enterprise development, using ordinary javabean instead of EJB technology. Can manage the dependencies between objects and objects, we do not need to set up objects, all of this work to the container to complete, with low coupling, the code is not aggressive, the server has no dependency characteristics of the framework.
And this container, the IOC.

Understanding the IOC idea

The purpose of creating objects using IOC is to form dependencies between objects in a "passive" manner. The traditional development process, whether new or ordinary factory, requires the target object to actively create and proactively find the dependent objects it needs, the target object will distract his energy in the unnecessary non-business logic. The IOC injects well-established objects into the target object through Di (dependency injection).

How is the Spring IOC implemented specifically?

Key points of the spring IOC container:
* The managed object must be defined in the spring configuration file
* Constructors or Setter methods must be defined so that spring will inject objects into it.

1. Configure Applicationcontext.xml

<Beansxmlns= "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-3.2.xsd ">    <BeanID= "Userdao4mysqlimpl"class= "Com.bjsxt.spring.dao.UserDao4MySqlImpl"/>    <BeanID= "Userdao4oracleimpl"class= "Com.bjsxt.spring.dao.UserDao4OracleImpl"/>    <BeanID= "Usermanager"class= "Com.bjsxt.spring.manager.UserManagerImpl">        <!--construction Method Injection <constructor-arg ref= "Userdao4oracleimpl"/> -         <!--Setter Method Injection -         < Propertyname= "Userdao"ref= "Userdao4oracleimpl"/>    </Bean></Beans>

2. Injected class:

 Package Com.bjsxt.spring.dao;  Public Interface Userdao {    publicvoid  Save (string Username, string password);}
 package   Com.bjsxt.spring.dao;  public  class  Userdao4mysqlimpl implements   Userdao { Span style= "COLOR: #0000ff" >public  void   Save (string Username, string password) {System.out.println ( "--------userdao4mysqlimpl.save ()-------" 
 Package Com.bjsxt.spring.dao;  Public class Implements Userdao {    publicvoid  Save (string Username, string password) {        System.out.println ("--------userdao4oracleimpl.save ()-------");}    }

3. The class being injected:

 Package Com.bjsxt.spring.manager;  Public Interface Usermanager {    publicvoid  Save (string Username, string password);}
 PackageCom.bjsxt.spring.manager;ImportCom.bjsxt.spring.dao.UserDao; Public classUsermanagerimplImplementsUsermanager {/*** Two ways: If you need to inject an object into this class, create an object property first, or write a constructor or Settet method. *      */    PrivateUserdao Userdao;/*Public Usermanagerimpl (Userdao userdao) {This.userdao = Userdao; } */     Public voidSave (string Username, string password) { This. Userdao.save (username, password); }     Public voidSetuserdao (Userdao Userdao) { This. Userdao =Userdao; }}

4. Test class:

 Packagecom.bjsxt.spring.client;Importorg.springframework.beans.factory.BeanFactory;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;ImportCom.bjsxt.spring.manager.UserManager; Public classClient { Public Static voidMain (string[] args) {/*Traditionally, the relationship between classes is established through the new object * Usermanager Usermanager = new Usermanagerimpl (new Userdao4oracleimpl ());        Usermanager Usermanager = new Usermanagerimpl (new Userdao4mysqlimpl ()); Usermanager.save ("Zhang San", "123");*//*** IOC idea to parse an XML file through a factory class and create objects in a "reflection" manner:*/Beanfactory Factory=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); Usermanager Usermanager= (Usermanager) factory.getbean ("Usermanager"); Usermanager.save ("Zhang San", "123");/*** IOC thought of the actual execution process, which is why the setter method or constructor method is required:*///Usermanagerimpl Usermanager = new Usermanagerimpl ();//Usermanager.setuserdao (New Userdao4mysqlimpl ());//Usermanager.save ("Zhang San", "123");    }}

Spring IOC Injection method:
    • Setter principle: In the target object, define the properties and setter methods of the dependent objects that need to be injected ; "Let the IOC container invoke this setter method", and inject the dependent object instantiated by the IOC container into the target object by setter. Encapsulated in the properties of the target object.
    • Constructor principle: provides a construction method for the target object, adding a dependent object parameter to the constructor method . When an IOC container is parsed, the constructor method is called automatically when the target object is instantiated, and the IOC only needs to assign values to the parameters in the constructor, and the dependent objects instantiated by the IOC as arguments to the constructor. "Interface Injection principle: provide an interface implementation for the dependent object, inject the interface into the target object, realize the effect of injecting the implementation class of the interface." For example HttpServletRequest HttpServletResponse interface Note: This is the way IOC provides it, and the IOC technology in spring does not implement that kind of injection. "
    • Method Injection Principle: Define a common method in the target object to set the return value of the method to the type of dependent object that needs to be injected . This method is called through the IOC container, and the dependent object it creates is returned to the target object as the return value of the method.
Specific Implementation

Three methods in the implementation of the main is injected and applicationcontext.xml different, the specific wording including the configuration of the parameters are as follows:
Action

Spring Framework Learning (2) IOC learning

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.