Spring知识点分析之ioc

本文深入探讨Spring框架的核心概念——控制反转(IoC)与依赖注入(DI),通过实例演示如何利用Spring容器管理和创建对象,提升开发效率。同时,文章分析了IoC/DI的优缺点,以及在实际项目中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring有两大核心,其一是控制反转/依赖注入(ioc),本文将仔细介绍该知识点的实际应用,从而凸显其特点。

一、介绍

       ioc是一种设计思想,并非技术。使用该设计思想意味着对象的创建将从传统 对象内部转为由Spring容器

      直接控制(整个生命周期),所以从这这种角度来看,控制权发生转变了,因此可以用控制反转来形容;同

     时对象也有容器直接注入给需要调用的对象,所以从这种角度看称为依赖注入。

     传统设计:

    

     ioc设计:

    

     IOC/DI优缺点

     优点:①将对象的创建交给容器,提高开发效率

     缺点:①对象的创建时通过反射来实现的,因此会有一定的效率损耗。

二  实例

     1 创建java project

     2 下载jar包

        Spring集成包下载地址:https://repo.spring.io/release/org/springframework/spring

     3 实体类 User.java

package com.spring;

public class User {
	private Integer id;
	private String  name;
	private String address;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
}

     4 applicationContext.xml(src根目录下)

<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-3.0.xsd">
	
        <!---spring创建bean->
        <bean class="com.spring.User">
           <!--通过set给name属性注入值-->
	   <property name="name" value="石义宾"/>
	</bean>
</beans>

     5 测试类

package com.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
                //加载并初始化配置文件
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
                //获取bean(对象)
		User user = (User)applicationContext.getBean(User.class);
		
		System.out.println(user.getName());
	}
	

}

 

     6 项目结构

       

          

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值