1. 程式人生 > >Spring中類型自動裝配--byType

Spring中類型自動裝配--byType

log ext setw println create cat ssp XML ret

在Spring中,“類型自動裝配”的意思是如果一個bean的數據類型與其它bean屬性的數據類型相同,將自動兼容裝配它。 例如,一個“persion” bean 公開以“ability”類數據類型作為屬性,Spring會找到ability類相同的數據類型,並自動裝配它的Bean。如果沒有匹配找到,它什麽也不做。
package auto_w;

/**
 * Created by luozhitao on 2017/8/8.
 */
public class ablity {

    public void setWrite_able1(String write_able1) {
        
this.write_able1 = write_able1; } public String getWrite_able1() { return write_able1; } private String write_able1; }

package auto_w;

/**
 * Created by luozhitao on 2017/8/8.
 */
public class Person {

    public void setLity(ablity lity) {
        this.lity = lity;
    }

    
public ablity getLity() { return lity; } private ablity lity; }

package auto_w;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by luozhitao on 2017/8/8.
 */
public class p_app {

    public
static void main(String [] args){ ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml"); Person person=(Person)context.getBean("person"); System.out.println(person.getLity().getWrite_able1()); } }

 <bean id="person" class="auto_w.Person" autowire="byType"></bean>
    <bean id="ablity" class="auto_w.ablity">
        <property name="write_able1" value="write"/>
    </bean>

Spring中類型自動裝配--byType