简体   繁体   English

在春季自动布线(属性名称和Bean名称必须相同)

[英]Autowiring in spring (property name and bean name must be same)

public class B {

    public B(){
        System.out.println("B is created");
    }

    public void print(){
        System.out.println("hello b");
    }

}

class B.java B.java类

public class A {

    B c;
    public A(){

        System.out.println("a is created");
    }

    public B getB(){
        return c;
    }

    public void setB(B c){
    this.c =c;
    }

    void print(){
        System.out.println("hello a");
    }

    void display(){
        print();

        c.print();
    }
}

class A.java A.java类

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
<bean id="b" class="B"></bean>

<bean id="a" class="A" autowire="byName"></bean>

</beans>

applicationcontext.xml applicationcontext.xml

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");

        A a1 = context.getBean("a",A.class);
        a1.display();

    }
}

Test .java 测试.java

i was going through the tutorials on autowiring in spring by using "byName" mode. 我正在通过使用“ byName”模式查看有关春季自动装配的教程。 and it says- The byName mode injects the object dependency according to name of the bean. 它说-byName模式根据bean的名称注入对象依赖项。 In such case, property name and bean name must be same. 在这种情况下,属性名称和bean名称必须相同。 It internally calls setter method. 它在内部调用setter方法。

but in this application the property name and the bean name both are different but it still works fine,so how this autowiring is working even though the both names are different? 但是在此应用程序中,属性名称和Bean名称都不同,但仍然可以正常工作,因此即使这两个名称不同,此自动装配如何工作?

It says property name , not field name . 它说的是属性名称 ,而不是字段名称

Property name in this case is inferred from the setter method name as defined by the JavaBeans naming convention ( setB -> b ), thus property name and bean name are the same. 在这种情况下,属性名称是根据JavaBeans命名约定( setB > b )所定义的setter方法名称来推断的,因此属性名称和bean名称相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM