Spring学习笔记

概念
POJO:Plain Ordinary Java Object 简单的Java类,即只含有一些属性和其get set 方法,不含有其他业务逻辑的Java类(简单的实体类)。它的作用是装载数据,作为数据存储的载体。
JavaBean百度百科对javabean的介绍
API(Application Programming Interface):是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。百度百科
IOC(Inversion of Control):控制反转,即依赖关系的转移,百度百科

依赖注入:对象与对象之间依赖关系的实现,包括接口注入,构造注入,set方法注入。Spring只支持后两种。Spring的依赖注入的基本思想为:明确地定义组件接口,独立开发各个组件,然后根据组件的依赖关系组装运行。
自动装配:使Spring自动识别如何装配Bean的依赖关系,有助于减少甚至消除配置<property> 元素和<constructor-arg> 元素。
自动检测:使Spring能够自动识别哪些类需要被配置成Spring Bean,从而减少<bean> 的使用。
AOP(Aspect Oriented Programming):面向方面编程。将日志,安全,事务管理等服务(或功能)理解成一个“方面”。百度百科
BeanFactory:spring使用BeanFactory来实例化、配置和管理对象,但是它只是一个接口,里面有一个getBean()方法。我们一般都不直接用BeanFactory,而是用它的实现类ApplicationContext,这个类会自动解析我们配置的applicationContext.xml,然后根据我们配置的bean来new对象,将new好的对象放进一个Map中,键就是我们bean的id,值就是new的对象。
具体介绍转载自这里

Spring 主要特点:
1.基于pojo的轻量级和最小侵入性的
2.通过以来注入和面向对象
3.基于切面和惯例进行声明式面层
4.通过切面和模板减少样板式代码

Bean的生命周期
1.Spring对Bean进行实例化
2.Spring 将值和Bean的引用注入Bean对应的属性中
3.如果Bean实现了BeanNameAware接口,Spring将Bean的ID传递给setBeanName()方法
4.如果Bean实现了BeanFactoryAware接口,Spring将调用setBeanFactory()接口方法,将BeanFactory容器实例传入。
5.如果Bean实现了ApplicationContextAware接口,Spring将调用setApplicationContext()接口方法,将应用上下文的引用传入。
6.如果Bean实现了BeanPostProcessor接口,Spring将调用他们的postProcessBeforeInitialization()方法。
7.如果Bean实现了Initialization接口,Spring将调用他们的afterPropertiesSet()接口方法。类似的,如果Bean使用init-method声明了初始化方法,该方法也会被调用。
8.如果Bean实现了BeanPostProcessor接口,Spring将调用他们的postProcessAfterInitialization()方法。
9.此时此刻,Bean已经准备就绪,可以被应用程序使用了,他们将一直驻留在应用上下文中,知道该应用上下文被销毁。
10.如果Bean实现了DisposableBean接口,Spring将调用它的destroy()接口方法。同样,如果Bean使用destroy-method声明了销毁方法,该方法也会被调用。

创建Bean的方法
1、通过构造器注入对象引用;
<bean id="" class=""><constructor-arg value="" />或<bean id="" class""><constructor-arg ref=""/>
2、通过工厂方法创建Bean
<bean id="" class="" factory-method=""/>

Bean的作用域

<bean id="" class="" scope="singleton">//默认情况,容器分配bean时总是返回bean的同一个实例
<bean id="" class="" scope="prototype">//每次请求时都为bean产生一个新的实例,即允许bean的定义可以被实例化任意次(每次调用都创建一个实例)

此外还有request、session、global-session作用域。

注入Bean属性
注入简单值

<bean id="" class="">
    <property name="属性名" value="属性值" />
</bean>

<bean id="" class="">
    <property name="属性名" ref="其他已声明的Bean">
</bean>
<bean id="" class="">
    <property name="属性名">
    <bean class="">   //内部bean

若在xml头部加入P命名空间,即

<beans ...........................
xmlns:p="http://www.springframework.org/schema/p"
..............................>

则可以

<bean id="" class="" 
    p:name="value"
    p:name-ref="bean's ID" />

装配集合分为四种:<list> / <set> / <map> / <props>
当bean的属性为数组或java.util.Collection接口的实现时使用 list 或 set ,map对应java.util.Map,props对应java.util.Properties,map和props都可以配置键值对组成的集合,二者区别在于props的键和值都必须是String类型,而map则可以是任意类型。

<bean id="" class="">
    <property name="">
        <list>
            <ref bean="" />
            <ref bean="" />
        </list>
    </property>
</bean>

<bean id="" class="">
    <property name="">
        <map>
            <entry key="" value-ref="Spring上下文引用的其他bean" /> 
        </map>
    </property>
</bean>

<bean id="" class="">
    <property name="">
        <props>
            <prop key="" >XXXXX</prop>
        </props>
    </property>
</bean>

一般bean的属性初始值都为null,但有些则默认为非空值,如果想设置属性值为null,可用<null/>:
<property name="初始值为非空的属性的名"><null/></property>

自动装配Bean属性
Spring提供了四种不同的自动装配Bean的方式:byName、byType、constructor、autodetect 。

byName和byType

<bean id="A" class="" autowire="byName">
<bean id="Ax1" class="">
A这个Bean里如果有名为Ax1的属性,则可以通过byName的自动装配模式将id="Ax1"的这个Bean(即Ax1这个Bean)装配到A的Ax1属性中。

<bean id="B" class="" autowire="byType">
<bean id="C" class="" >
    <property name="" value="" />
若B Bean 中存在一个名为Bx1的属性,并声明为byType的自动装配模式,则B Bean 将自动查找和名为Bx1的属性类型相同的属性装配到B Bean 的Bx1属性中。如果有多个类型同时匹配,则会报错。

关于byName和byType的一些
在一些博客和网站上看到,byType匹配是在其他Bean中查找名为Bx1的属性值进行匹配,暂时不知道哪个对。例如下面这个例子
byType具体实例如下:
转自here


This mode specifies autowiring by property type. Spring container looks at the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If matches are found, it will inject those beans otherwise, it will throw exceptions.

For example, if a bean definition is set to autowire byType in configuration file, and it contains a spellChecker property of SpellChecker type, Spring looks for a bean definition named SpellChecker, and uses it to set the property. Still you can wire remaining properties using <property> tags. Following example will illustrate the concept where you will find no difference with above example except XML configuration file has been changed.

第一个类
package com.tutorialspoint;

public class TextEditor {
   private SpellChecker spellChecker;
   private String name;

   public void setSpellChecker( SpellChecker spellChecker ) {
      this.spellChecker = spellChecker;
   }
   public SpellChecker getSpellChecker() {
      return spellChecker;
   }

   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }

   public void spellCheck() {
      spellChecker.checkSpelling();
   }
}

第二个类
package com.tutorialspoint;

public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }

   public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
   }

}

测试文件:
package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");

      TextEditor te = (TextEditor) context.getBean("textEditor");

      te.spellCheck();
   }
}


不用autowire="byType" 的 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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- Definition for textEditor bean -->
   <bean id="textEditor" class="com.tutorialspoint.TextEditor">
      <property name="spellChecker" ref="spellChecker" />
      <property name="name" value="Generic Text Editor" />
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
   </bean>

</beans>

使用autowire="byType" 的 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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- Definition for textEditor bean -->
   <bean id="textEditor" class="com.tutorialspoint.TextEditor" 
      autowire="byType">
      <property name="name" value="Generic Text Editor" />
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id="SpellChecker" class="com.tutorialspoint.SpellChecker">
   </bean>

</beans>

显示结果为
Inside SpellChecker constructor.
Inside checkSpelling.

在Spring中<bean> 元素的primary属性默认为true,所以如果想让某个Bean变为优先匹配的Bean,则需要将非首选的Bean的primary属性设置为false。
还可以将不想匹配到的Bean标注为 autowire-candidate=“false”

<bean id="" class="xxx.xxx.xxx" autowire="byType" primary="false">
<bean id="" class="xxx.xxx.xxx" autowire="byType" autowire-candidate="false">

constructor:

<bean id="A" class="xxx.xxx.B" autowire="constructor" />

Spring在构造A Bean时将审查B的构造器,并尝试从其他Bean中找到可以匹配这个构造器的构造器,并将参数传入进行匹配。

autodetect:
先尝试用constructor,如果失败则用byType。

@Autowired
@Autowired 注解采用byType方式自动装配。
@Qualifier(”Bean‘s ID”) 缩小@Autowired匹配Bean的范围,将@Autowired 的 byType匹配限定为匹配对应Bean名的Bean。

@Inject
@Inject对应的是@Named(”bean’s ID”)

使用JSR-330的@Qualifier创建新的注解@A

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface A{
}

关于几种依赖注入注解的区别请看这里
Spring各种依赖注入注解的区别

自动检测Bean

<beans xmlns=.......>
    <context:component-scan
        base-package="要扫描的包">
    </context:component-scan>
</beans>

AOP

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值