一、Spring下载
官网地址:https://spring.io/projects/spring-framework
二、创建项目
idea新建一个spring项目,创建一个spring全局库。
项目文件结构如下:
需要导入commons-logging,否则运行时会报错。
三、HelloWorld程序
1、定义bean类
package com.chan.spring.bean;
/**
* Student Bean
* @author Chan
*/
public class Student {
private String name;
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void hello() {
System.out.println("我是" + name);
}
}
2、配置bean实例对象
创建src目录下创建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对象 -->
<bean id="stu1" class="com.chan.spring.bean.Student">
<property name="name" value="小明" />
</bean>
</beans>
3、在主程序中使用bean实例
package com.chan.spring.app;
import com.chan.spring.bean.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 应用类,程序入口
* @author Chan
*/
public class Application {
public static void main(String[] args) {
//创建Spring IOC容器对象
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//从IOC容器获取对象
Student stu1 = (Student) context.getBean("stu1");
//调用对象hello方法
stu1.hello();
}
}
4、编译运行
四、总结
Spring的特点
- 控制反转(IOC),通过依赖注入的方式(DI)
- 面向切面编程(AOP)
- 轻量级,对象不依赖于Spring
- 容器,Spring是容器,创建和管理对象的生命周期
- 一站式,可以整合其他框架和类库,自己也提供了MVC和JDBC框架。