spring自动装配

来源:互联网 发布:淘宝网店装修策略 编辑:程序博客网 时间:2024/05/16 09:18

  1。spring.xml配置文件

        <!--                           自动装配的方式                      1.ref根据属性Property的名字装配bean,这种情况,Customer设置了autowire="byName",Spring会自动寻找与属性名字“person”相同的bean,找到后,通过调用setPerson(Person person)将 其注入属性。 2.autowire值为byName           根据属性Property的数据类型自动装配,这种情况,Customer设置了autowire="byType",Spring会总动寻找与属性类型相同的bean,找到后,通过调用setPerson(Person person)将其注入。                 3.autowire值为byType 这种情况下,Spring会寻找与参数数据类型相同的bean,通过构造函数public Customer(Person person)将其注入                                                 4.autowire值为 constructor        -->               <!--  <bean id="customer" class="Auto.Customer">          <property name="person" ref="person"></property>       </bean>  -->               <!-- <bean id="customer" class="Auto.Customer" autowire="byName"/> -->      <!--  <bean id="customer" class="Auto.Customer" autowire="byType"/> -->            <bean id="customer" class="Auto.Customer" autowire="constructor"/>              <bean id="person" class="Auto.Person">            <property name="age" value="21"></property>            <property name="name" value="李跃"></property>             <property name="sex" value="男"></property>       </bean>
2.
package Auto;public class Person {    private String name;    private String age;    private String sex;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}}

3.
package Auto;import org.springframework.beans.factory.annotation.Autowired;public class Customer {   public Person person;      public Customer(Person person){   this.person=person;   }    public void fun(){   System.out.println(person.getAge());   }        public Person getPerson() {return person;}public void setPerson(Person person) {this.person = person;}}
4.

package Auto;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class autotest {        public static void main(String args[]){        ConfigurableApplicationContext cf=new ClassPathXmlApplicationContext("spring-mvc.xml");        Customer person=(Customer)cf.getBean("customer");        System.out.println(person.getPerson().getAge());        }}