·Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建。简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架。
· Spring下载:spring的官网改版之后,就不支持直接下载了,可以在这里点击下载。
·下载当前最新版本(4.3.1.RELEASE)后,可以看到目录如下:
|-docs :文档和api
|-libs:jar包
|-schema :不懂(笑)
·spring需要依赖apache的log包(commons-logging-1.2-bin) ,可以在官网下载。
·现在就可以建立第一个java-spring程序了。
① 首先定义一个学生类
package com.fuwh.spring;
public class Student {
private String name;
private int age;
public Student() {
System.out.println("类被初始化");
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
public class Student {
private String name;
private int age;
public Student() {
System.out.println("类被初始化");
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
②在classpath下定义一个配置文件bean.xml(名字可以随便取)。
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans.xsd">
6
7 <!-- services -->
8
9 <bean id="student" class="com.fuwh.spring.Student" lazy-init="default">
10 <property name="name" value="fengzi"></property>
11 <property name="age" value="23"></property>
12 </bean>
13
14 </beans>
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans.xsd">
6
7 <!-- services -->
8
9 <bean id="student" class="com.fuwh.spring.Student" lazy-init="default">
10 <property name="name" value="fengzi"></property>
11 <property name="age" value="23"></property>
12 </bean>
13
14 </beans>
③ 编写测试类 1 package com.fuwh.spring;
2
3 import org.springframework.context.ApplicationContext;
4 import org.springframework.context.support.ClassPathXmlApplicationContext;
5
6 public class Spring01 {
7
8 public static void main(String[] args) {
9
10 ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
11 System.out.println(ac.getBean("student"));
12 }
13 }
3 import org.springframework.context.ApplicationContext;
4 import org.springframework.context.support.ClassPathXmlApplicationContext;
5
6 public class Spring01 {
7
8 public static void main(String[] args) {
9
10 ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
11 System.out.println(ac.getBean("student"));
12 }
13 }
这样一个基于spring的程序就完成了,spring程序和普通程序不一样的是,不再需要new一个对象,而是将对象的创建交给了spring容器,也就是所谓的Ioc。