实验4---Spring IoC-xml配置
创始人
2025-05-31 07:40:05

Spring IoC-xml配置

一.实验任务

通过该实验掌握利用Spring xml配置方式实现控制反转IoC(依赖注入),掌握Spring的Ioc注入方式:属性注入和构造注入。

二、实验结果

1 关键代码

1.1注入普通类及属性

1.Person的代码

public class Person {

private String name;

public void sayHello(){

System.out.println("hello, i am " + name);

}

//省略get set等

}

2.spring的xml配置文件关键代码

3.MyTest.java代码

public class MyTest{

public static void main(String[] args) {

ApplicationContext apc = new ClassPathXmlApplicationContext("applicationContext.xml");

Person person = (Person) apc.getBean("person");

person.sayHello();

}

}

4.运行效果图

1.2配置类及使用bean—设值(属性)注入

1.在applicationContext.xml的关键代码

2.MyTest2.java代码

public class MyTest2{

public static void main(String[] args) {

ApplicationContext apc = new ClassPathXmlApplicationContext("applicationContext.xml");

//second 配置类及使用bean

Chinese chinese = (Chinese) apc.getBean("chinese");

chinese.useAxe();

American american = (American) apc.getBean("american");

american.useAxe();

}

}

3.效果图

1.3配置类及使用bean--构造注入

1.applicationContext.xml的关键代码

2.MyTest3.java关键代码

public class MyTest3 {

public static void main(String[] args) {

ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");

//构造注入

France france=(France)context.getBean("france");

france.useAxe();

}

}

3.效果图

相关内容

热门资讯

投资者提问:请问董秘,当前中日... 投资者提问:请问董秘,当前中日关系陷入僵局乃至谷底之际,公司有规划更多使用国产光刻胶等材料来替代日系...
富德生命人寿咸阳中心支公司被罚... 12月16日金融一线消息,据咸阳金融监管分局行政处罚信息公开表显示,富德生命人寿保险股份有限公司咸阳...
市场监管总局:抓紧推进出台《互... 转自:北京日报客户端记者16日从市场监管总局获悉,市场监管总局正抓紧推进《互联网平台反垄断合规指引》...
天奇股份:锂电循环业务夯实产业... 12月16日,江西天奇金泰阁集团(简称“天奇金泰阁”)资本赋能发展大会在江西龙南举行。会上,天奇股份...
「侠客岛」他们用上了“AI分身...   炒股就看金麒麟分析师研报,权威,专业,及时,全面,助您挖掘潜力主题机会! (来源:海外网)来源...