idea creates a Spring project to implement IOC

Spring IOC

1 Overview

IOC full name: Inverse of Control, Inversion of Control, IOC is not actually a technology, but a design idea.
In short: the object that originally required the program to actively create new is now reversed and handed over to the spring container to create.

2. Create a Spring project in the idea

Check Spring and Web Application (others remain default)

insert image description here
Select the project name and project path - click Finish (the jar package required by spring will be automatically downloaded)
insert image description here
Create a new configuration file (Spring Conifg file)
insert image description here
Enter the file name in the pop-up box - click OK
insert image description here

3. Simple IOC implementation

Create a User class, ignore unimportant methods, and print out the information of the User class. The code is as follows:

public class User {
    
    

  private String name; //姓名

  private  Integer  age; //年龄

  private String sex;  //性别

  //忽略一些方法(get和set)
  
 //重写toString打印user信息
  @Override
  public String toString() {
    
    
      return "User{" +
              "name='" + name + '\'' +
              ", age=" + age +
              ", sex='" + sex + '\'' +
              '}';
  }
}

Configure the Bean.xml file to associate the attributes of the User class and assign values. The code is as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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.xsd">
       
    <!--bean标签对应着User类,其中property标签name表示user变量名称value代表给其赋的值-->
    <bean id="user" class="com.demo.User">
        <property name="name" value="李小立"/>
        <property name="age" value="22"/>
        <property name="sex" value=""/>
    </bean>
</beans>

Finally, create a new demo class DemoMain

public class DemoMain {
    
    
    public static void main(String[] args) {
    
    
        //创建Spring上下文加载bean.xml
        ApplicationContext app=new ClassPathXmlApplicationContext("bean.xml");
        //获取user实例
        User user =  (User)app.getBean("user");
        //打印user
        System.out.println(user);
    }
}

got the answer
insert image description here

Copyright statement: This article is an original article by the blogger and may not be reproduced without the permission of the blogger https://blog.csdn.net/qq_44614710/article/details/86763053

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324117195&siteId=291194637
Recommended