1、通过在Eclipse IDE中安装Spring Tool Suite(STS)插件可以很方便地创建Spring、SpringMVC及Spring Boot工程,在Eclipse IDE中安装Spring Tool Suite(STS)插件,请参照《Spring插件安装说明.docx》
2、下载Spring相关jar包
a、logging jar包下载地址:https://commons.apache.org/proper/commons-logging/download_logging.cgi,这里下载1.2版。
b、Spring jar包下载地址:http://repo.springsource.org/libs-release-local/org/springframework/spring/,这里下载4.3.10版。
3、第一个Spring程序
a、创建一个普通Java的工程;
b、向工程中添加如下jar包;
①、创建lib文件夹,将如下jar包拷贝到该文件夹中
②、由于是Java工程,所以为了使这些jar包起作用需要先选择这些jar包——>鼠标右键点击Build Path——>Add to Build Path;如果是Java Web工程只需将这些jar包拷贝到WEB-INF中lib文件夹即可;
c、在com.lq.test中创建HelloWorld类:
package com.lq.test;
public class HelloWorld {
private String name;
public void setName(String name) {
this.name = name;
}
public void sayHello() {
System.out.println(name +" say HelloWorld");
}
}
d、创建Spring XML文件:
①、选中src目录——>鼠标右键,选中并点击“Other…”项——>找到并打开“Spring”节点,出现下图:
②、选择“Spring Bean Configuration File”子节点,点击“Next>”按钮,出现下图:
③、在“File name”文本框输入配置文件的文件名(这里为applicationContext.xml),点击“Next>”按钮,出现下图:
说明:在创建Spring XML文件前需要先导入相应的jar包,否则上面红框区域不会出现那些Spring命名空间项。
e、在applicationContext.xml中配置HelloWorld类:
<?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属性:用于获取IOC容器中的Bean对象,具有唯一性 -->
<!-- class属性:指定Bean对象由哪个类创建,为类的全类名 -->
<bean name="helloWorld" class="com.lq.test.HelloWorld">
<!-- 为name属性赋值 -->
<property name="name" value="zhangsan"></property>
</bean>
</beans>
说明:该xml文件用于配置一个或多个Java对象。
f、从IOC容器中获取实例对象并调用sayHelloWorld方法:
package com.lq.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//创建Spring IOC容器对象
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//从IOC容器中获取Bean对象
HelloWorld helloWorld = (HelloWorld) applicationContext.getBean("helloWorld");
//调用sayHello方法
helloWorld.sayHello();
//关闭IOC容器
applicationContext.close();
}
}