前面1-9同系列的博文介绍了一些基本知识,是后面文章的基础。
后面所有的文章都只是记录一些使用方法和要点,依赖和pom的配置后面会有文章专门整理一下全面的配置。
入门
1. 什么是IOC的功能?
* IoC -- Inverse of Control,控制反转,将对象的创建权反转给Spring!!
* 使用IOC可以解决的程序耦合性高的问题!!
2.包结构和类
* com.demo1
* UserService -- 接口
* UserServiceImpl -- 具体的实现类
3. 想把UserServiceImpl实现类的创建交给Spring框架来管理,需要创建Spring框架的配置文件,完成配置
* 在src目录下创建applicationContext.xml的配置文件,名称是可以任意的,但是一般都会使用默认名称!!
* 引入spring的约束,需要先找到具体的约束头信息!!
* spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\html\xsd-config.html
* 具体的约束如下:
<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="userService" class="com.itcast.demo1.UserServiceImpl"/>
</beans>
4. 编写测试程序,采用Spring框架的工厂方式来获取到UserService接口的具体实现类!!
public void demo2(){
// 使用Spring的工厂:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
// 通过工厂获得类:
UserService userService = (UserService) applicationContext.getBean("userService");
userService.sayHello();
}
实际使用Spring开发web项目时不会这么使用。但是如果是开发可运行jar包时,使用Spring就会使用这种方式。
Spring bean标签配置文件
1. id属性和name属性的区别
* id -- Bean起个名字,在约束中采用ID的约束,唯一
* 取值要求:必须以字母开始,可以使用字母、数字、连字符、下划线、句话、冒号 id:不能出现特殊字符
* name -- Bean起个名字,没有采用ID的约束(不常用)
* 取值要求:name:出现特殊字符.如果<bean>没有id的话 , name可以当做id使用
* Spring框架在整合Struts1的框架的时候,Struts1的框架的访问路径是以/开头的,例如:/bookAction
2. class属性 -- Bean对象的全路径
3. scope属性 -- scope属性代表Bean的作用范围
* singleton -- 单例(默认值)
* prototype -- 多例,在Spring框架整合Struts2框架的时候,Action类也需要交给Spring做管理,配置把Action类配置成多例!!
* request -- 应用在Web项目中,每次HTTP请求都会创建一个新的Bean
* session -- 应用在Web项目中,同一个HTTP Session 共享一个Bean
* globalsession -- 应用在Web项目中,多服务器间的session
4. Bean对象的创建和销毁的两个属性配置(了解)
* 说明:Spring初始化bean或销毁bean时,有时需要作一些处理工作,因此spring可以在创建和拆卸bean的时候调用bean的两个生命周期方法
* init-method -- 当bean被载入到容器的时候调用init-method属性指定的方法
* destroy-method -- 当bean从容器中删除的时候调用destroy-method属性指定的方法
* 想查看destroy-method的效果,有如下条件
* scope= singleton有效
* web容器中会自动调用,但是main函数或测试用例需要手动调用(需要使用ClassPathXmlApplicationContext的close()方法)