spring ioc---DI進階之引入其他bean
阿新 • • 發佈:2018-12-12
官方xsd文件中關於ref的參考說明
原文連結:http://www.springframework.org/schema/beans/spring-beans.xsd
1.標籤ref:
Defines a reference to another bean in this factory or an external factory (parent or included factory).
2.bean標籤內的屬性ref:
A short-cut alternative to a nested "<ref bean='...'/>" element.
3.也可使用內部bean的方式,引入其他的bean.
使用的類物件
package siye;
public class Person
{
}
package siye;
public class User
{
Person person;
public void setPerson(Person person)
{
this.person = person;
}
}
xml配置檔案,檔名`config.xml`
<bean id="thePerson" class="siye.Person" /> <!--使用ref標籤或屬性 --> <bean id="obj0" class="siye.User"> <property name="person"> <ref bean="thePerson" /> </property> </bean> <bean id="obj1" class="siye.User"> <property name="person" ref="thePerson" /> </bean> <!--使用inner-bean --> <bean id="obj2" class="siye.User"> <property name="person"> <bean class="siye.Person" /> </property> </bean>
測試類
package siye; import org.springframework.context.support.ClassPathXmlApplicationContext; public class UnitTest { public static void main(String[] args) { String path = "classpath:/siye/config.xml"; ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(path); System.out.println(context.getBean("obj0", User.class)); System.out.println(context.getBean("obj1", User.class)); System.out.println(context.getBean("obj2", User.class)); context.close(); } }