Spring带你飞系列 三: 注解之 @Autowired

直接上代码

步骤一: 定义一个实体类Person

package com.dd;

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

public class Person {

public StringgetName() {

return name;

    }

public void setName(String name) {

this.name = name;

    }

public StringgetAddress() {

return address;

    }

public void setAddress(String address) {

this.address = address;

    }

public int getAge() {

return age;

    }

public void setAge(int age) {

this.age = age;

    }

private  Stringname;

    private  Stringaddress;

    private  int age;

}


步骤二: 定义另一个类Customer ,其中含属性Person ,并指明属性person为 @Autowired

package com.dd;

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

public class Customer {

@Autowired

    private Person person;

    public Person getPerson() {

return person;

    }

public void setPerson(Person person) {

this.person = person;

    }

public int getType() {

return type;

    }

public void setType(int type) {

this.type = type;

    }

public StringgetAction() {

return action;

    }

public void setAction(String action) {

this.action = action;

    }

private int type;

    private Stringaction;

}

步骤三:

新增Spring-config文件:  beans.xml  (注:此配置文件中未配置Customer BEAN中含有属性Person)

<context:annotation-config />

<bean id="CustomerBean" class="com.dd.Customer">

    <property name="action" value="buy" />

    <property name="type" value="1" />

<bean id="PersonBean" class="com.dd.Person">

    <property name="name" value="LaoWang" />

    <property name="address" value="Near" />

    <property name="age" value="29" />


步骤四: 编写测试类

package com.dd;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public  static  void main(String[] args){

ApplicationContext apc =new ClassPathXmlApplicationContext("Beans.xml");

        Customer customer = (Customer)apc.getBean("CustomerBean");

        System.out.println(customer.getPerson().getName());

    }

}

步骤五: run运行查看结果



如上,可见在beans.xml配置文件中未指明Customer包含属性Person 情况下,在代码中对    private Person person; 使用了注解@@Autowired 时, Person对象会被自动注入到 Customer对象中; 

此为@Autowired注解最常用法;

注: beans.xml中必须有配置 <context:annotation-config />  ,否则@Autowired不会生效执行;