Spring基础知识梳理

来源:互联网 发布:opengl 游戏编程 编辑:程序博客网 时间:2024/06/05 14:17

官方文档地址:
https://linesh.gitbooks.io/spring-mvc-documentation-linesh-translation/content/publish/21-1/introduction-to-spring-web-mvc-framework.html

1 Spring概要
Spring现在主要是一站式服务,Spring Core Container是 其中最重要的组件,一般与其他框架一起用。
Spring容器最重要的作用?是管理Bean,Spring容器中的全部对象都是Bean。
Spring通过什么来管理Bean? XML文件
Spring的底层会执行什么代码?

String classStr=....;Class  clazz=Class.forName(classstr);Object obj=class.newInstance();

依赖注入的两种方式?设值注入与构造注入

设值注入:通过成员变量setter方法来注入被依赖的对象,这种方式简单、直观

private class Chinese implements Person{private Axe axe;public void setAxe(Axe axe){this.axe=axe;}//实现Person接口的useAxe()方法public void useAxe(){System.out.println(axe.chop());}}
<bean id="chinese"  class="org.crazyit.app.service.impl.Chinese"><property  name="axe"  ref="stoneAxe"></bean>

bean中id是什么?指定改Bean的唯一表示,Spring根据id属性值来管理Bean,程序通过id属性值来访问该Bean实例。
bean中class是什么?该Bean的实现类,不能实现接口,必须是全路径实现类,Spring容器会使用XML解析器读取该属性值,并利用反射来创建该实现类的实例。
Spring会自动检查bean里面的property元素,只要发现property元素会调用默认的构造器创建Bean实例,立即调用对应的setter方法为Bean的成员变量注入值。

public class Chinese implements Person{private Axe axe;public Chinese(Axe axe){this.axe=axe;}//实现Person接口的useAxe()方法public void useAxe(){System.out.println(axe.chop());}
<bean id="chinese" class="org.crazyit.app.service.impl.Chinese"><constructor-arg ref="steelAxe"></bean>

Spring自动找到bean中的constructor,根据constructor-arg来调用构造器。

如何使用Spring容器的核心接口?Spring容器有两个核心接口:BeanFactory和ApplicationContext,其中ApplicationContext是BeanFactory的子接口。

BeanFactory最常见DefaultListableBeanFactory。

ApplicationContext最常见的实现类有:FileSystemApplicationContext、ClassPathCXmlApplicationContext、AnnotationConfigApplicationContext。

2 Bean的基本定义