1. 开发环境:MyEclipse10.7 + jdk1.7
1.新建项目web SpringTest
2.导入Spring核心包
2.目录结构(红色部分jar 是必须要的)
3*****
package
com.zcjy.xuexi;
public
class
HelloWorld {
private
String
name
;
public
String getName() {
return
name
;
}
public
void
setName(String name) {
this
.
name
= name;
}
//一个无参的构造器,有一个默认的无参构造器
public
HelloWorld() {
//
TODO
Auto-generated constructor stub
}
//给一个无参的方法
public
void
say(){
System.
out
.println(
"你好:"
+
name
);
}
}
4****
<?
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:p
=
"http://www.springframework.org/schema/p"
xsi:schemaLocation
=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"
>
<!-- 配置Bean,
class: 类全名,通过反射的方式在Ioc容器中创建Bean(要求bean 中有一个无参的构造器)
id: 标识容器中的bean,id唯一。
id可以指定多个名字,名字之间可以用逗号,分号,或者空格分隔
-->
<
beans
>
<
bean
id
=
"id2"
class
=
"com.zcjy.xuexi.HelloWorld"
>
<
property
name
=
"name"
value
=
"世界"
></
property
>
</
bean
>
</
beans
>
</
beans
>
5***
package
com.zcjy.xuexi;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public
class
Testhw {
public
static
void
main(String[] args) {
/**ApplicationContext(代表Ioc容器) 是一个接口
ClassPathApplicationContext 是在类的路径下加载配置文件
Spring 提供了2种类型的Ioc 容器的基本实现。beanFacory和ApplicationContext
beanFactory:Ioc 容器的基本实现,面向Spring
ApplicationContext是BeanFactory的子接口,面向Spring框架开发者,大部分用ApplicationContext
ApplicationContext 有两种实现类
1.ClassPathXmlApplicationContext :从类路径下加载配置文件
2.FileSystemXmlApplicationContext :从系统文件下加载配置文件
*/
//
创建ioc 容器
ApplicationContext ac=
new
ClassPathXmlApplicationContext(
"ApplicationContext.xml"
);
//从Ioc 容器中获取bean 实例
HelloWorld hw = (HelloWorld)ac.getBean(
"id2"
);
hw.say();
}
}