1.搭建Spring环境
下载jar
https://maven.springframework.org/release/org/springframework/spring/
spring-framework-4.3.9.RELEASE-dist.zip
开发spring至少需要使用的jar(5个+1个):
1)spring-aop.jar 开发AOP特性时需要的JAR
2)spring-beans.jar 处理Bean的jar <bean>
3)spring-context.jar 处理spring上下文的jar <context>
4)spring-core.jar spring核心jar
5)spring-expression.jar spring表达式
三方提供的日志jar
6)commons-logging.jar 日志
2.编写配置文件
为了编写时有一些提示、自动生成一些配置信息:
方式一:增加sts插件
可以给eclipse增加 支持spring的插件:spring tool suite(https://spring.io/tools/sts/all)
下载springsource-tool-suite-3.9.4.RELEASE-e4.7.3a-updatesite.zip, 然后在Eclipse中安装:Help下的Install new SoftWare.. 点击 Add
方式二:
直接下载sts工具(相当于一个集合了Spring tool suite的Eclipse): https://spring.io/tools/sts/
新建:bean configuration .. - applicationContext.xml
3.开发Spring程序(IOC)
ApplicationContext conext = new ClassPathXmlApplicationContext("applicationContext.xml") ;
//执行从springIOC容器中获取一个 id为student的对象
Student student = (Student)conext.getBean("student") ;
可以发现,springioc容器 帮我们new了对象,并且给对象赋了值
代码实现:
创建实体类:Student.java
package com.entity;
public class Student {
private int stuNo;
private String stuName;
private int stuAge;
public int getStuNo() {
return stuNo;
}
public void setStuNo(int stuNo) {
this.stuNo = stuNo;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
@Override
public String toString() {
return "Student [stuNo=" + stuNo + ", stuName=" + stuName + ", stuAge=" + stuAge + "]";
}
}
创建配置文件:applicationContext.xml src目录下
<?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">
<!-- 该文件中产生的所有对象,被spring放入了一个 称之为spring ioc容器的地方 -->
<!-- id:唯一标识符
class:指定类型
-->
<bean id="student" class="com.entity.Student">
<!-- property该class所代表类的属性
name:属性名
value:属性值
-->
<property name="stuNo" value="2"></property>
<property name="stuName" value="ls"></property>
<property name="stuAge" value="24"></property>
</bean>
</beans>
创建测试类:Test.java
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.entity.Student;
public class Test {
public static void main(String[] args) {
// //原始方式
// Student student = new Student();
// student.setStuNo(1);
// student.setStuName("zs");
// student.setStuAge(23);
// System.out.println(student);
//使用IOC容器
//spring上下文对象,加载spring配置文件:context
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//直接从springIOC容器中获取一个id为student的对象
Student student =(Student)context.getBean("student");
System.out.println(student);
//1.new
//2.对象属性的赋值
}
}