Spring learn note 2

来源:互联网 发布:java时钟代码 编辑:程序博客网 时间:2024/06/07 02:51

Wiring beans-装配Bean

Spring的一个重要的基本特征就是Dependency injection (DI). 个人理解DI为一个名词, 其行为就是Wire-装配, 更确切的说是在Spring容器的应用上下文中自动或手动扫描组件Bean, 并完成装配(connection)的过程.

Spring的DI和AOP, 以及other Framework中, 都和Java annotation 极为类似. Three phrase:

  1. Definition, Declaration-定义和声明
  2. Mark-定义完注解就需要在需要的位置去标记使用
  3. Resolution and Process-解析处理. 想产生结果, 就必须使用相应的处理器去寻找并解析Mark Bean

Spring offers three primary wiring mechanisms:

  1. Explicit configuration in XML
  2. Explicit configuration in Java
  3. Implicit bean discovery and automatic wiring

1. Automatically wiring beans

Spring从两个角度来实现自动化装配:

  1. Component scanning
  2. Autowiring

想创建可被发现的Bean, 需要在你想要被发现的Bean上增加@Component. 虽然添加了组件, 不过组件扫描默认是不开启的,需显示配置(虽然是自动装配, 但需告知Spring容器你使用的装配scheme).
e.g, @Component对应的Javaconfig为@ComponentScan, 对应的XML为<context:component-scan base-package="bp" />

在测试时使用ContextConfiguration(classes=Javaconfig.class) 便能使Spring Application Context通过对应的配置文件创建Beans.

实现自动装配. 通过在对应的Bean上添加@Autowired注解.

2.Wiring beans with Java

创建JavaConfig类的关键在于为其添加@Configuration 注解,@Configuration 表明这个类是一个配置类,该类应该包含在Spring上下文中如何创建bean的细节。
通过使用@Bean 注解在JavaConfig中来生命bean,其返回一个要注册在Spring上下文中的bean对象实例。默认情况下,Spring中的Bean都是单例的。方法体中包含了最终产生bean实例的逻辑,根据不同场景自己实现。

3.Wiring beans with XML

基本语法:<bean id="name" class="package.Class" />

3.1 Initializing a bean with constructor injection

  • <constructor-arg>
  • c- 命名规则
3.1.1 bean引用注入
  1. <constructor-arg ref="reference" />
  2. c:构造器参数名-ref=”要注入bean ID”
  3. 使用索引来识别构造器.c:_index-ref="beanID"
3.1.2 Literal 字面量注入
  1. <constructor-arg value="literal " />
  2. c:_index="beanID"
3.1.3 Collections 集合注入
  <constructor-arg>       <list>                  <value> literal </value>           ...           OR           <ref bean="reference" />           ...       </list>   </constructor-arg>

####3.2 Setting properties

  1. <property />
  2. p- 命名规则
3.2.1 bean引用注入
  1. <property name=" " ref=" " />
  2. p:name-ref=" "
3.2.2 Literal 字面量注入
  1. <property name=" " value=" " />
  2. p:name=" "
3.2.3 Collections 集合注入
  <property name=" ">       <list>                  <value> literal </value>           ...           OR           <ref bean="reference" />           ...       </list>   </constructor-arg>

OR

<util:list id=" ">    <value> literal </value>    ...    OR    <ref bean="reference" />    ...</util:list>

作为一个通用规则,对强依赖使用构造器注入,对可选性依赖使用属性注入。
Choose order:
1. First: automatic wiring
2. Second: Javaconfig
3. Finally: XML config

实际项目中经常见到混合配置(Mixed configuration)

原创粉丝点击