spring简单使用

spring全家桶,为软件开发中的各种问题,提供了各种解决方案的框架。最核心的是控制反转和aop。

控制反转,可以不用再显示的创建对象和赋值对象。全部通过spring的IOC容器和注解来实现。

1. bean

被spring容器管理的java对象,就叫做bean。在spring的开发中,大部分的对象创建,都可以让spring容器来管理。

bean的创建

  1. bean可以通过xml实例化
  <bean id = "exampleBean" class = "examples.ExampleBean" init-method = "init"/>   #(调用init来实例化)
  <bean id = "exampleBean" class = "examples.ExampleBean" destroy-method = "destroy"/> #(销毁的时候,调用destroy)
  1. 也可以通过注解来实例化如@component,但需要在xml配置bean搜索范围
# 会在base package包下面搜索,被@Component,@service 注解的类,自动注入到beanfactory
<context:component-scan base-package="com.digisky.female.common,name.skycat.common,com.digisky.female.princess.server" />

bean的生命周期

bean 生命周期

  • BeanPostProcessor,可以在创建bean的前后,扩展添加自定义的操作。比如bean创建完成后,对bean其中的字段,再单独处理赋值
  • BeanDefinitionRegistryPostProcessor,实现这个接口的bean。在xml中配置,会调用它的两个方法(可以编程实现些spring初始化的逻辑,比如class的scan

对bean更多的控制

  1. 如果出现多个实现。可以对其中一个component指定@primary,来作为优先的component来自动装配。在自动装配@autowired时,也可以指定@Qualifier来限定装配的component。
  2. bean默认是单例的singleton。可以指定@Scope("xxx") 注解来表明不同的作用域。其它常用的有: prototype:每次getBean的时候,创建新的bean。 session:每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP session内有效 request:表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP request内有效
  3. 工厂类的bean,实现FactoryBean接口,以拦截创建bean的过程(在BeanDefinitionRegistryPostProcessor接口 指定factorybean的类)
  4. Interceptor拦截器。在每个web请求的前后增加逻辑

2. bean容器

bean容器也叫IoC容器,最常用的就是ApplicationContext,需要实现BeanFactory接口。主要实现了GetBean方法,通过Bean类名,Bean class对象等各种方式获取容器内的Bean对象。

容器有完善的事件机制。事件继承自ApplicationEvent,容器本身实现了ApplicationContextEvent事件。可以监听context refreshstartstopRequestHandler(用户请求结束后会触发)等事件。

3. spring头

自定义ramcache的前缀,更丰富配置和配置检查

<ramcache:config id="cacheService" lockAspect="true">
    <ramcache:accessor ref="accessor" />
    <ramcache:querier ref="querier" />
    <ramcache:constants ref="ramcache_constants" />
    <ramcache:persist type="TIMING" config="0 * * * * *">
        <ramcache:persistor name="per_5_minute" type="TIMING" config="10 */5 * * * *" />
    </ramcache:persist>
    <ramcache:entity>
        <ramcache:package name="com.digisky.gal.warstates.**.service"/>
    </ramcache:entity>
</ramcache:config>

前缀的定义在

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:ramcache="http://www.skycat.name/game/common/ramcache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.skycat.name/game/common/ramcache http://www.skycat.name/game/common/ramcache/ramcache-1.0.0.xsd
">

xsd文件的位置即使是url,也可能直接取得本地Resource下的文件。

Updated: