你的认同是对我最大的赞美。

Spring框架中的依赖注入

  依赖注入(DI : Dependency Injection)是基于.xml配置文件内节点的书写。

  注入类型:

      1.设置注入,调用了Bean的setXXX()进行值注入

   普通属性(value值表示要显示的字符串)

    <property name="name" value="托尼"></property>
    <property name="age" value="20"></property>

   域属性(ref属性指向的是普通属性的name值)

    <property name="myCar" ref="name"></property>

   构造注入

    <bean id="stu2" class="cn.tony.entity.Student">

      <constructor-arg index="0" value="托尼"></constructor-arg>
      <constructor-arg index="1" value="20"></constructor-arg>
      <constructor-arg index="2" ref="mmCar"></constructor-arg>
    </bean>

   命名空间p注入(p:name对应实体类中的name属性。如,p:info对应了User实体类中的info属性):

     使用p命名空间进行改进配置,注意使用前要先添加p命名空间的声明。

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

      在.xml中书写如下:

     <!-- p标签注入 -->

     <bean id="stu3" class="cn.tony.entity.User"
      p:name="国庆放假买手机" p:info="100块">
     </bean>

  使用注解进行注入:

    在.xml中添加context命名空间的声明

      xmlns:context="http://www.springframework.org/schema/context" 

 

    配置如下节点

      <!--  base-package指向的是包文件,实体类包  -->

      <context:component-scan base-package="cn.tony.entity">

      </context:component-scan>

 

    在entity包下的UserInfo实体类中书写如下:

 1 <!--  Component相当于Bean的id属性  -->
 2       @Component("info")
 3       public class UserInfo {
 4       @Value("yellow")
 5       private String color;
 6 
 7       public String getColor() {
 8         return color;
 9       }
10 
11       public void setColor(String color) {
12         this.color = color;
13       }
14 
15       }
UserInfo实体类

 

posted @ 2016-10-10 10:27  Tony_copper  阅读(316)  评论(0编辑  收藏  举报
 Tony