会员
众包
新闻
博问
闪存
赞助商
HarmonyOS
Chat2DB
所有博客
当前博客
我的博客
我的园子
账号设置
会员中心
简洁模式
...
退出登录
注册
登录
🈲小呆
博客园
首页
新随笔
联系
订阅
管理
学习报告
新建一个空的 Java 项目,命名为【spring】
新建一个名为【lib】的目录,并添加进必要的 jar 包,导入项目
在 Packge【pojo】下新建一个【Source】类:
package pojo;
public
class
Source {
private String fruit;
// 类型
private String sugar;
// 糖分描述
private String size;
// 大小杯
/* setter and getter */ }
在 【src】 目录下新建一个 【applicationContext.xml】 文件,通过 xml 文件配置的方式装配我们的 bean
<?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
name=
"source"
class=
"pojo.Source">
<
property
name=
"fruit"
value=
"橙子"/>
<
property
name=
"sugar"
value=
"多糖"/>
<
property
name=
"size"
value=
"超大杯"/>
</
bean>
</
beans>
在 Packge【test】下新建一个【TestSpring】类:
package test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Source;
public
class
TestSpring { @
Test
public void test(){
ApplicationContext context = new
ClassPathXmlApplicationContext( new
String[]{
"applicationContext.xml"} );
Source source = (
Source) context.getBean(
"source");
System.out.
println(source.getFruit());
System.out.
println(source.getSugar());
System.out.
println(source.getSize()); } }
运行测试代码,可以正常拿到 xml 配置的 bean
总结:
传统的方式:
通过new 关键字主动创建一个对象
IOC方式:
对象的生命周期由Spring来管理,直接从Spring那里去获取一个对象。 IOC是反转控制 (Inversion Of Control)的缩写,就像控制权从本来在自己手里,交给了Spring。
posted @
2021-09-09 17:20
禁小呆
阅读(
32
) 评论(
0
)
收藏
举报
刷新页面
返回顶部
公告