这篇博客用于某些人快速回忆Spring
快速搭建Spring环境
- 首先第一步倒入spring所要依赖的jar包
commons-logging-1.1.3.jar 日志
spring-beans-3.2.5.RELEASE.jar bean节点
spring-context-3.2.5.RELEASE.jar spring上下文节点
spring-core-3.2.5.RELEASE.jar spring核心功能
spring-expression-3.2.5.RELEASE.jar spring表达式相关
- 在src项目下创建一个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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
>
<!-- 通过容器来管理javabean,通过构造函数的方式来创建javabean -->
<bean id="user" class="com.project.bean.UserBeanImp"></bean>
</beans>
- 在测试类中通过IOC容器获取对象
//1、读取配置文件实例化一个IoC容器
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//2、从容器中获取Bean,注意此处完全“面向接口编程,而不是面向实现”
IUserBean user=(UserBeanImp) ac.getBean("user");
通过上面简单的步骤就可以快速的搭建好Spring的环境了!接下来是一些常用的一些属性了。
标签中常用属性
Bean的作用域(scope)
Spring提供“singleton”和“prototype”两种基本作用域
singleton:指“singleton”作用域的Bean只会在每个Spring IoC容器中存在一个实例。对于所有获取该Bean的操作Spring容器将只返回同一个Bean(实例存入缓存池,每次获取都是从缓存池中取出,其生命周期由IOC控制
)。
<bean class="xxx.xxx.xxx.MyDome1" scope="singleton"/>
prototype:即原型,指每次向Spring容器请求获取Bean都返回一个全新的Bean,相对于“singleton”来说就是不缓存Bean,每次都是一个根据Bean定义创建(对象不存入缓存池生命周期不完全由IOC控制
)。
<bean class="xxx.xxx.xxx.MyDome2" scope="prototype"/>
定义Bean的生命始末(init-method,destroy-method)
在Bean创建或者销毁时由IOC调用的方法,当然初始化时调用的方法和销毁时所调用的方法是需要在Bean中加入。
<bean id="userservice" class="xxx.xxx.Bean"
init-method="init" destroy-method="destory"></bean>
当然初始化时调用的方法和销毁时所调用的方法是需要在Bean中加入。
public class Bean {
public void init(){
System.out.println("这是自己定义的init");
}
public void destory(){
System.out.println("这是自己定义的destory");
}
}
延迟初始化Bean( lazy-init )
延迟初始化也叫做惰性初始化,在默认情况下在IOC容器产生时同时也会生成IOC容器中所有的Bean对象。如果将Bean的lazy-init设置为true时,只有在调用该Bean对象时Ioc容器才会创建。
<bean id="helloApi"class="xxx.xxx.Bean" lazy-init="true"/>