环境搭建
Spring 开发我们可以使用 Eclipse ,但是 Eclipse 中必须安装Spring开发插件:Spring tool suite,或者直接到网络上下载安装了了插件的 Eclipse,这种 Eclipse 就叫做 Spring tool suite。
在 官网 我们就能看到 Spring 提供的安装方式选择,我这里的环境是 Eclipse ,所以下载了 Eclipse 的 Windows 版的 Spring tool suite
注意这里来下载下来的是一个 jar 包,把后缀改成 zip 解压 , 再解压其中 contents 压缩包 , 然后运行里面的 SpringToolSuiteX.exe 就行
这里其实下载就是一个 Eclipse , 只是这个 Eclipse 集成了 Spring . 其他和 Eclipse 没什么差别
初体验 IOC
反转控制,颠覆了我们获取资源的方式
Person 类
package com.test.helloworld;
public class Person {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Person() {
System.out.println("无参构造函数");
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
Spring 如何获取对象呢 ? 我们原来的获取对象方式如下:
//1 获取Person对象
Person person = new Person();
//2 设置对象的属性值
person.setName("蜘蛛精");
person.setAge(18);
//使用对象
System.out.println(person);
那么 Spring 怎么获取呢?
-
最基本Spring的开发也需要以下的jar文件
-
spring-beans-XXX.RELEASE.jar
-
spring-context-XXX.RELEASE.jar
-
spring-core-XXX.RELEASE.jar
-
spring-expression-XXX.RELEASE.jar
-
把上述的包添加到工程,并且添加到类路径.
-
-
创建 Spring 的配置文件( 比较原始的配置方式 )
其实这里也可以不用这种方式 , 也可以直接新建一个 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"> </beans>
-
编写配置文件
<?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="person" class="com.test.helloworld.Person"> <property name="name" value="小明"></property> <property name="age" value="20"></property> </bean> </beans>
这里解释一下标签
-
bean : 表示配置一个 bean,这个 bean 会在 IOC 容器启动的时候,被 IOC 容器加载(实例化),并且在 IOC 容器中管理这个 bean
-
id : bean的名称,是一个唯一的名称
-
class : 这个bean对应的类型的全类名
-
property : 这个标签表示给 IOC 容器中管理的这个 bean 设置属性
-
name : 属性名 ( 对应的是JavaBean风格的属性名 , 也就是 setter 方法 )
-
value : 需要设置的属性值
-
-
-
-
启动
我们再 main 函数书写下面代码
//1 .启动SpringIOC容器,并获得这个容器对象 ApplicationContext act = new ClassPathXmlApplicationContext("hello-world.xml"); //2 .从IOC容器中获取bean对象 Person person = (Person) act.getBean("person"); //3 .使用bean System.out.println(person); }
结果就是打印 Person 信息
无参构造函数 Person [name=小明, age=20]