Simple use of IOC in spring

Source: Internet
Author: User

Spring's IOC is mainly dependent injection, there is a dependency injection based on the constructor and through the setting value injection, here I only simple implementation of the method of value injection, through spring dependency management, we can easily understand the dependencies between the layers, reducing the coupling between the layers, We can not focus on the management and creation of objects, we just need to go to the bean factory to apply, so that our more attention can be put into the real code implementation, not to care about the creation and destruction of code. , and then simply set the value to inject.

  1. Let's start by simply creating a class of students and teachers
     Public class Student {    publicvoid  Outhi () {        System.out.println ("I am a student");}    }
     public  class   teacher {  Student Stu;  public   Student Getstu () { return   Stu;  public  void   Setstu (Student Stu) {  Stu;   public  void   Lalal () {Stu.outhi ();    System.out.println ( "Lalala" ); }}

    Notice that the teacher class here depends on the student class, that is, the need to call the student object in the teacher class, here we use the method of setting value injection.

  2. Next you need to go to the XML file to do the corresponding configuration
    <bean name= "Stu"  class= "Com.domain.Student" ></bean>        <bean name= "Teacher"  class= "Com.domain.teacher" >    <property name= "Stu" ref= "Stu" ></property>    </bean >

  3. Finally, apply the corresponding object in the main function
     Public Static void Main (string[] args) {        //  TODO auto-generated method stub         new Classpathxmlapplicationcontext ("Applicationcontext.xml");         Teacher Tea= (teacher) Ctx.getbean ("Teacher");         Tea.lalal ();    }


Simple use of IOC in spring

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.