如何使用IoC

本文介绍了如何使用Maven创建Java工程,并添加Spring框架的依赖。接着展示了传统方式下手动创建Student类对象的过程,然后转向Spring的IoC(Inversion of Control)概念,通过XML配置文件管理对象,实现对象的自动创建。详细步骤包括配置文件的编写,以及如何从IoC容器中获取并使用对象。
摘要由CSDN通过智能技术生成

创建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);


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值