Spring是什么?
- Spring是一个开源框架,为了简化java企业级开发而生.使用Spring框架可以使java程序开发变得更加的简单.
- Spring是一个ICO和AOP(面向切面程序)容器框架.
- Spring还具有整合其他框架的功能


Eclipse的Spring插件
- 如果使用的是Eclipse工具开发,那么可以安装Spring插件:SPRING TOOL SUITE


Spring项目基础环境

- Spring项目还需要有一个配置文件:spring.config.xml(如果使用的是IDEA工具创建的spring项目,该文件会自动生成)
使用IDEA创建Spring项目
- 选择创建一个新的项目或者一个新的模块
- 这里以创建一个新的模块(module)为例
- 选择Spring项目,IDEA支持自动下载spring4.3和和spring3.2版本的jar包

- 选择模块名称

- IDEA自动下载所需文件中

- 完成之后选择apply应用

- 如果IDEA没有创建spring-config.xml文件,可以收工来创建,选择项目右键—>[new]—>[xml Configuration File]—>[spring Config]


Spring版HelloWorld
- 创建一个HelloWorld程序类
package mao.shu.spring;
public class HelloWorld {
private String userName;
public void setUserName(String userName) {
this.userName = userName;
}
public void hello(){
System.out.println("Hello World = userName"+userName);
}
}
- 配置spring-config.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="mao.shu.spring.HelloWorld">
<property name="userName" value="Xiemaoshu"/>
</bean>
</beans>
- 使用Spring实例化Bean对象,并调用hello()方法,大致分为三个步骤
- 创建SpringICO容器
- 从容器中 获取bean对象
- 调用hello()方法
package mao.shu.mian;
import mao.shu.spring.HelloWorld;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Begin {
public static void main(String[]args){
ApplicationContext app =
new ClassPathXmlApplicationContext("spring-config.xml");
HelloWorld helloWorld = (HelloWorld) app.getBean("helloworld");
helloWorld.hello();
}
}
- 最好将spring-config.xml文件放置到path路径下(src)
- 运行结果
- 从输出中可以发现,spring自动将对象中的"userName"属性值了
