您的位置:首页 > 编程语言 > Java开发

Spring系列【05】@Autowired详解(补充)

2014-12-14 12:48 609 查看
注意:以下内容基于Spring2.5以上版本。

一共讲解四种@Autowired的用法,第一种构造方法上的使用已在前一节讲解过,本次讲解其它三种。

现在有一个老板Boss.java,他拥有一台车和一个办公室。

public class Boss {
private Car car;
private Office office;

// 省略 get/setter

@Override
public String toString() {
return "car:" + car + "\n" + "office:" + office;
}
}


Spring配置文件如下:声明AutowiredAnnotationBeanPostProcessor类

<?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-2.5.xsd"> 
<bean class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/>

<bean id="boss" class="com.baobaotao.Boss"/>

<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="001"/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" 红旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>


1. @Autowired 进行成员变量自动注入的代码:其中Car和Office类自己搞定。如果这个都搞不定,建议不要往下看了,回头学java基础吧。

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

public class Boss {

@Autowired
private Car car;

@Autowired
private Office office;

//省略getter/setter方法
}


2. @Autowired 在setter方法上的使用。

package cn.com.xf;

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

public class Boss {
private String name;
private int age;

private Car car;
@Autowired   //注意位置
public void setCar(Car car) {
this.car = car;
}

public String getName() {
return name;
}

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

@Override
public String toString() {
return "Boss [name=" + name + ", age=" + age + ", car=" + car + "]";
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

//必须要有空的构造方法
public Boss(){}

  //会自动把setCar方法注入到构造方法需要的入参
public Boss(Car c){
this.car=c;
}
}


3. @Autowired 在任何方法上的使用,只要该方法定义了需要被注入的参数即可实现Bean的注入。

当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有 @Autowired 注释时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐