Spring的《注解装配》- @autowired

本文详细介绍了Spring中@Autowired注解的使用,包括通过属性域、set方法、构造器方法注入,以及@required属性和@Qualifier限定器的配合使用,帮助理解Spring的自动装配机制。
摘要由CSDN通过智能技术生成

这篇博客主要介绍通过@autowired 注解来装配bean,包括以下内容:
1. 通过属性域注入
2. 通过set方法或则其他方法注入
3. 通过构造器方法注入
4. @autowired 的required属性
5. @autowired 的限定器@Qualifier

1. 通过属性域注入

下面通过一个实例来说明@autowired 注解实现属性域注入:
(1)entity
蛋糕类

package spring.ch2.topic2;

/**
 * Created by louyuting on 17/1/20.
 * 注入属性,记得属性必须要写setter方法  不然就会抛出异常,注入失败.
 * 蛋糕类
 */
public class Cake {
   
    private String name = "";

    public String getName() {
        return name;
    }

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

厨师类

package spring.ch2.topic2;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by louyuting on 17/1/22.
 */
public class Chief {
   
    @Autowired
    private Cake cake = null;//自动注入的就不需要setter方法了

    private String name = "";

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

    public Cake makeOneCake() {
        System.out.println(getName() + " make " + cake.getName());
        return cake;
    }
}

这里需要注意的是,虽然我们的cake属性域是赋值为null,但是当spring容器启动时,j就会通过@Autowired标签注入cake对象。

(2)配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="blueberryCheese"
          class="spring.ch2.topic2.Cake"
          p:name="blueberryCheese---Cake" scope="prototype">
    </bean>

    <bean id="jack"
          class="spring.ch2.t
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值