spring简单案例
使用软件:STS
搭建spring运行时环境
1.加入JAR包
1)Spring自身JAR包:spring-framework-4.0.0.RELEASE\libs目录下
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELE2ASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
2)commons-logging-1.1.1.jar
注:将以上所有的jar包复制到项目中的lib目录下并全选所有jar包–>右键–>build path–>config bulid path
2.在Spring Tool Suite工具中通过如下步骤创建Spring的配置文件
1)File->New->Spring Bean Configuration File
2)为文件取名字 例如:applicationContext.xml
创建一个类:Person.java
package com.atguigu.spring.mod;
public class Person {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
}
常规方法操作对象
创建一个测试类Test.java
package com.atguigu.spring.mod;
public class Test {
public static void main(String[] args){
Person person = new Person();
person.setId(1);
person.setName("zhangsan");
System.out.println(person);
}
}
spring管理对象
1.创建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>:定义spring管理的一个对象
id:该对象的唯一标识,注意不能重复,在类型获取bean的过程中可以不设置
class:该对象所属类的全限定名
-->
<!-- 通过反射创建对象 -->
<bean id="person" class="com.atguigu.spring.mod.Person">
<!--
<property>:为对象的某个属性赋值
name:属性名
value:属性值
-->
<property name="id" value="1111"></property>
<property name="name" value="小明"></property>
</bean>
</beans>
2.创建一个测试类TestBySpring.java
package com.atguigu.spring.mod;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBySpring {
public static void main(String[] args) {
//初始化容器
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//通过getBean()获取对象
Person person = (Person) ac.getBean("person");
System.out.println(person);
}
}
注:IOC和DI
反转控制(IOC):对象的管理权(创建、赋值等)由程序员交给了spring容器
依赖注入(DI):bean对象依赖于属性 向属性注入资源(赋值)
总结: IOC 就是一种反转控制的思想, 而DI是对IOC的一种具体实现。