zoukankan      html  css  js  c++  java
  • Spring Autowire

    Autowire:自动装配

    autowire的实现方式有2种,但是其最终是通过autoWire来修饰bean,并让bean在上下文中具有自动装配的能力.

    实现autowire的方法有2种:

    第一种在配置直接配置bean xml文件,如:<bean id="customer" class="com.ric.demo.Customer" autowire="constructor"></bean>

    <bean id="person" class="com.ric.demo.Person">
    <property name="name" value="john"/>
    <property name="age" value="20"/>
    <property name="gender" value="1"/>
    </bean>
    这种方式可以让bean在上下文中通过 autowire的值判断自动装配规则,byName是通过名字匹配,byType是通过类型匹配(这时候上下文中只能有一种这种类型的bean否则会报错),default(不会装配),contructor(根据构造器来装配,这时候会把上下文中同名的bean当作参数传入构造器中来装配)


    第二种:通过@Autowired注解来实现,这种实现方式需要在自动装配的地方加上@Autowired来修饰,然后具体spring如何扫描呢:
    1、通过org.springframework.beans.factory.annotation.
    AutowiredAnnotationBeanPostProcessor 来实现,在定义beans的上下文中加上
    <bean class="
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">来处理
    2、把xml中这个bean 对应的xml配置给注释掉,并在beans中加上自动扫描的包,然后在要装配的bean的class前加上@Component,对应的属性上加上@Autowired就可以了。
    两种方式都是通过将bean置于上下文中,这样context可以通过扫描或者配置来给对应的bean自动装配,关键是要让你要暴露的bean置于上下文当中
    这种通过@Autowired注解(包括以上1,2)来自动装配时@Autowired可以这样@Autowired(required=false)来修饰你的自动装配是不是必要的,如果为false时那么当被装配的属性为空不会出现异常报错。这时还有另外一个注解配合使用能够实现第一种方法中的byName的方式。eg.
    @Autowired(required=false)// 装配不上时不会出现异常
    @Qualifier("PersonBean1")// 匹配上下文与Qualifier中参数相同名的bean








     
  • 相关阅读:
    usaco-ariprog1-pass
    usaco-crypt1-pass
    usaco-barn-repair-pass-KISS
    usaco-mixing milk-pass
    面试HR
    LCS求最长公共子序列(DP)
    毕业随想(转载)
    0-1背包问题(DP)
    排序算法
    二叉搜索树的实现 java
  • 原文地址:https://www.cnblogs.com/codetime/p/6296689.html
Copyright © 2011-2022 走看看