如何使用IoC

创建Maven工程,pom.xml添加依赖

<?xml version="1.0" encoding="UTF-8"?>2<project xmlns="http://maven.apache.org/POM/4.0.0"3         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"4         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">5    <modelVersion>4.0.0</modelVersion>6​7    <groupId>com.southwind</groupId>8    <artifactId>aispringioc</artifactId>9    <version>1.0-SNAPSHOT</version>10​11    <dependencies>12        <dependency>13            <groupId>org.springframework</groupId>14            <artifactId>spring-context</artifactId>15            <version>5.0.2.RELEASE</version>16        </dependency>17    </dependencies>18​19​20</project>

创建实体类Student

package com.southwind.entity;

import lombok.Data;

@Data
public class Student {
    private long id;
    private String name;
    private int age;
    
}```
传统的开发方式,手动new Student

package com.southwind.test;

import com.southwind.Student;

public class Test {
public static void main(String[] args) {
Student student = new Student();
student.setId(1L);
student.setName(“张三”);
student.setAge(22);
System.out.println(student);
}
}

通过IoC创建对象,在配置文件中添加需要管理的对象。XML格式的配置文件,文件名可以自定义。

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=“http://www.springframework.org/schema/beans”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xmlns:context=“http://www.springframework.org/schema/context”

   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context">
<bean id="student" class="com.southwind.entity.Student">
    <property name="id" value="1"></property>
    <property name="name" value="张三"></property>
    <property name="age" value="22"></property>
</bean>
从IoC中获取对象,通过id获取

// 加载配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“spring.xml”);
Student student = (Student) applicationContext.getBean(“student”);
System.out.println(student);



版权声明:本文为m0_45045268原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。