一:新建项目
打开ecplise,File—new——java Project,给项目起个名字
2. 加入jar包,新建一个文件夹lib,把spring所用的jar包赋值进去
3.在类路径下创建一个spring的XML文件applicationContext.xml;
<?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 id="helloWorld" class="com.dhx.HelloWorld">
<property name="name" value="shangguigu"></property>
</bean>
</beans>
4.根据上面的步骤做完,spring的环境算是搭建好了。下面开始测试
二:测试
1.创建一个HelloWorld类
public class HelloWorld {
private String name;//属性
public void setName(String name) {
this.name = name;
}
public void hello() {//方法
System.out.println("hello world "+name);
}
}
2.在applicationContext文件中配置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">
<!--
id:我们从IOC容器取出的唯一标识,一般是类名的首字母小写
class:类的全路径
property:代表属性的配置,其中name是调用name的set方法(注意set方法的名字要保持一致),value是赋值
-->
<bean id="helloWorld" class="com.dhx.HelloWorld">
<property name="name" value="shangguigu"></property>
</bean>
</beans>
3.我们创建一个Mian类来测试
public class Main {
public static void main(String[] args) {
//创建spring容器对象
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
//从IOC中获取bean的实例
HelloWorld hw=(HelloWorld) ctx.getBean("helloWorld");
//调用方法
hw.hello();
}
}
4.结果