《Spring》——HelloSpring

本文介绍如何使用Spring框架通过XML配置实现依赖注入,包括创建Bean、配置属性及在Java代码中获取和使用这些Bean的过程。

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

3、HelloSpring
beans.xml

<?xm1 version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2081/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	https: //www.springframework.org/schema/beans/spring-beans.xsd">


	<!--
		使用Spring来创建对象,在ESpring这些都称为Bean
		类型 变量名= new 类型();
		HeLlo heLLo = new HeLLo();
		id =变量名
		cLass = new 的对象;
		property 相当于给对象中的属性设置一个值!
	-->

	<bean id="hello" class="com.kuang.pojo.Hello">
		<!--
			Value:具体的值,可以是基本数据类型
			ref :引用Spring容器中创建好的对象
		-->
		<property name="str" value="Spring" / >
	</bean>
</beans>

MyTest.java

public class MyTest {
public static void main(string[ ] args) {
	//获取Spring的上下文对象!(固定写法,配置xml写法),也可以叫做获取ApplicationContext ;拿到Spring的容器
	ApplicationContext context = new ClassPathXm1ApplicationContext("beans.xm1");
	//我们的对象现在都在Spring中的管理了,我们要使用,直接去里面取出来就可以!(直接get出来)
	He1lo hello = (Hello) context.getBean( "hello");
		System.out.println(hello.toString());
	}
}

总结:
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的.
反转︰程序本身不创建对象,而变成被动的接收对象.
依赖注入:就是利用set方法来进行注入的.
可以通过newClassPathXmlApplicationContext去浏览一下底层源码.
OK,到了现在,我们彻底不用再程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的loC一句话搞定:对象由Spring 来创建,管理,装配!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘二壮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值