Spring IOC

Spring AOP

IOC控制反转,传统的方式是自己直接控制对象,这种方式可称为“正转”;由IOC容器代为管理对象则称为“反转”。(自己做饭 —> 餐厅点餐)

1. 实现(简单工厂模式、工厂方法模式)

  • BeanFactory 是Spring基础接口
  • ApplicationContext(Spring上下文) 是 BeanFactory 接口 的扩展
<?xml version="1.0" encoding="UTF-8"?>
<beans 命名空间>
   <bean id="id" class="全类名">
       <property name="属性名1" value="属性值1"/>
       ....
   </bean>
    ....
</beans>

2. Bean定义

属性描述
class指定Bean类名,必选
name指定Bean唯一标识
scope作用域(singleton、prototype、request、session、global-session)
<constructor-arg ref=""/>基于构造函数依赖注入
<properties name="" ref=""/>基于setter依赖注入
autowiring自动装配
lazy-initialization延迟加载
init-method创建完毕回调
destroy-method销毁回调

3. 作用域

  • singleton:单例模式;

  • prototype:原型模式 ,多例;

  • request :每次HTTP请求创建新Bean,仅适用于WebApplicationContext 环境;

  • session:仅同一HTTP Session共享Bean,仅适用于WebApplicationContext 环境;

  • global-session: Portlet 应用环境,仅适用于WebApplicationContext 环境。

☆Portlet :web组件。

4. 生命周期(创建、销毁)

  • 创建: 实现InitializingBean 接口 afterPropertiesSet() 方法;
  • 销毁: 实现 DisposableBean 接口 destroy() 方法;
  • XML方式使用 init-method、destroy-method属性指定回调方法。

5. 注入集合

四种类型: list 、set、map、props(key-value类型均为String)

	<property name="list">
         <list>
            <ref bean="bean"/>
            <value>value</value>
         </list>
      </property>

      <property name="set">
         <set>
            <ref bean="bean"/>
            <value>value</value>
         </set>
      </property>

      <property name="map">
         <map>
            <entry key="key1" value="value"/>
            <entry key ="key2" value-ref="ref"/>
         </map>
      </property>

6. 自动装配

  • byNmae:通过参数名自动装配,容器自动匹配并装配和该Bean的属性具有相同名字的Bean;
  • byType:通过参数类型自动装配,容器自动匹配并装配和该Bean的属性具有相同类型的Bean,若匹配失败,则抛出异常;
  • constructor:类似byType,通过有参构造器自动装配,若匹配失败,则抛出异常。

7. 注解

  • @Required:用于Bean的setter方法,受影响的属性必须XML文件中配置,否则抛出 BeanInitializationException 异常;
  • @Autowired:自动连接Bean,可用于属性、setter和构造器;
  • @Qualifier:多个相同类型Bean根据 id 选择其一注入,结合@Autowired使用。

8. JSR-250注解

  • @PostConstruct@PreDestroy:分别对应init-methoddestroy-method
  • @Resource: @Autowired 和 @Qualifier 组合效果。

9. 基于java的配置

  • @Configuration:用于定义配置类,等价<beans></beans>;

  • @Bean:等价<bean><beans/>,默认方法名为id,返回值注入到 IOC 容器中;

  • @Import:从另一个配置类中加载Bean。

10. 监听上下文事件

实现 ApplicationListener<T> 接口的 onApplicationEvent方法

  • ContextRefreshedEvent : ApplicationContext 初始化或刷新时;
  • ContextStartedEvent : 使用start() 方法时;
  • ContextStoppedEvent :使用 stop() 方法时;
  • ContextClosedEvent:使用 close () 方法时;
  • RequestHandledEvent : 告诉所有Bean HTTP请求已经被服务。

11. 自定义事件

  1. 定义:继承ApplicationEvent并使用其构造器;
  2. 发布:实现ApplicationEventPublisherAware接口,通过ApplicationEventPublisher对象发布事件;
  3. 监听:实现ApplicationListener接口,onApplicationEvent方法处理,或使用**@EventListener**定义监听方法;
  4. 注册监听器到IOC容器。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值