下面将介绍如何在Eclipse中开发HelloSpring项目;
在Eclipse中新建一个项目HelloSpring,将所需的jar文件添加到项目中,需要注意的是Spring的运行依赖于commons-logging组件,需要将相关jar一起导入;项目所需的jar由下图所示
编写HelloSpring类,如下图所示:
package cn.springdemo;
/**
* 第一个Spring,输出"HelloSpring"
* @author 天晴时等烟雨
*
*/
public class HelloSpring {
//定义who属性,该属性的值将通过Spring框架进行设置
private String who=null;
/**
* 定义打印的方法
*/
public void print() {
System.out.println("Hello,"+this.who);
}
/**
* 获取who
* @return
*/
public String getWho() {
return who;
}
/**
* 设置who
* @param who
*/
public void setWho(String who) {
this.who = who;
}
}
接下来编写Spring配置文件,在项目的classpath根路径下创建applicationContext.xml文件(为方便与管理框架的配置文件,可在项目中创建专门的Source Folder,如resource目录,并将Spring配置文件创建在其根路径下),在Spring配置文件中创建HelloSpring类的示例并未who属性注入属性值.Spring配置文件内容入下所示:
<?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-3.2.xsd ">
<!--通过bean元素声明需要Spring创建的示例.该示例的类型通过class属性指定,并通过id属性为该示例制定一个名称
,并通过id属性Wie该示例指定一个名称,以便于访问 -->
<bean id="helloSpring" class="cn.springdemo.HelloSpring">
<!-- property元素用来为示例的属性赋值,此处实际是调用setWho()方法实现赋值操作 -->
<property name="who">
<!-- 此处将字符串"Spring"赋值给who属性 -->
<value>Spring</value>
</property>
</bean>
</beans>
在项目中添加测试方法,关键代码如下:
package cn.springdemo.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.springdemo.HelloSpring;
public class DemoTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//通过ClassPathXmlApplicationContext实例化Spring的上下文
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
//通过ApplicationConText的getBean()方法,根据id来获得Bean的实例
HelloSpring helloSpring=(HelloSpring)ctx.getBean("helloSpring");
//执行print()
helloSpring.print();
}
}
运行效果如下:
在以上代码中,ApplicationContext是一个接口,负责读取Spring配置文件,管理对象的加载,生成,维护Bean对象与Bean对象之间的依赖关系,负责Bean的生命周期等,ClassPathXmlApplicationContext是ApplicationContext 接口的实现类,用于从classpath路径中读取配置文件;
jar下载地址:链接:https://pan.baidu.com/s/1z5NVu6jMyF3mcAbmavOFlw
提取码:xjg9
本次项目下载地址:链接:https://pan.baidu.com/s/1hfPdSY8b8Y-YzYiAJjMeEQ
提取码:a9lg