Spring入门学习(一,入门案例)
解释图
- 通过上图可以看出Spring的作用,以及每一层的作用,这个也是一般web业务处理的流程
Spring机制
Bean、IOC/DI、AOP具体每个是什么意思,这里不再解释,可以参考官方文档,以及大牛博客,下面我直接讲解入门案例
入门案例
User
public class User {
private String name;
private Happy happy;
public Happy getHappy() {
return happy;
}
public void setHappy(Happy happy) {
this.happy = happy;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void say() {
System.out.println("你好"+name);
}
}
Happy
public class Happy {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void happy() {
System.out.println(name+"好玩");
}
}
Text01
以前我们是通过这样的方法使用User对象的,我们直接实例化出来,然而现在用Spring就不同了
public class Text01 {
public static void main(String[] args) {
//读取配置文件,并且实例化bean
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//通过ID拿到bean
User user=(User) ac.getBean("user");
//使用bean
user.say();
user.getHappy().happy();
//Spring中的bean不止一个,可以多次使用
Happy happy=(Happy) ac.getBean("happy");
happy.happy();
}
}
- 我们就可以不通过new从而拿到一个实例化的对象
- 这里主要是通过配置文件实现的依赖注入
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd">
<bean id="user" class="domain.User">
<property name="name" value="张三"></property>
<property name="happy" ref="happy"></property>
</bean>
<bean id="happy" class="domain.Happy">
<property name="name" value="成都"></property>
</bean>
</beans>
- 这里前面的头部文件不用管,使用的时候直接复制粘贴即可
- 主要注意下面的bean的配置
- id:就是我们要使用bean的时候,需要获取的一个标志(不能重复)
- class: 这个不用多说吧,就是一个实体类的位置
- property:属性的注入
- name:实体类中的属性名,别打错了
- value:我们需要写入的值,也就是等于属性的值
- ref:指向我们当前bean中的一个对象,通过ID指向,因为我们User对象中有个Happ的实例,所以配置了 ref=“happy”,就职指向happy的配置
- 下面通过一个表格介绍
id(key) | 实例(value) |
---|---|
user/happy | User实例 |
happy | Happy实例 |
Spring的bean就如同这个键值对一样的,我们存放进入的键值,然后我们根据键(ID)取出相应的值(实例对象)
同时我们也可以看出Spring的底层是基于一个反射实现的
总结
- 以上就是一个简单的Spring入门案例了
- 我们通过配置文件,成功的实现了依赖注入,我们通过配置文件中的property标签实现了对对象的实例化以及属性的赋值