依赖注入_引用其他的bean
生活随笔
收集整理的這篇文章主要介紹了
依赖注入_引用其他的bean
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
引用其它 Bean
組成應(yīng)用程序的 Bean 經(jīng)常需要相互協(xié)作以完成應(yīng)用程序的功能. 要使 Bean 能夠相互訪問, 就必須在 Bean 配置文件中指定對(duì) Bean 的引用
在 Bean 的配置文件中, 可以通過 <ref> 元素或 ref ?屬性為 Bean 的屬性或構(gòu)造器參數(shù)指定對(duì) Bean 的引用.?
也可以在屬性或構(gòu)造器里包含 Bean 的聲明, 這樣的 Bean 稱為內(nèi)部 Bean
<?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.xsd"> <!-- 配置Car, 屬性注入(set方法注入) --><bean id="car" class="com.learn.spring.beans.Car"><property name="brand" ><value>Audi</value></property><property name="crop" value="yiqi"></property><property name="price" value="400000"></property></bean><bean id="person" class="com.learn.spring.beans.Person"><property name="name" value="莫小貝"></property><property name="age" value="12"></property><!-- 引用其他的bean ref:指定要引用的bean --><property name="car" ref="car"><!-- <ref bean="car"/> --></property><!-- <constructor-arg value="" ref=""></constructor-arg> --></bean></beans> package com.learn.spring.test;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import com.learn.spring.beans.Book; import com.learn.spring.beans.Car; import com.learn.spring.beans.HelloWorld; import com.learn.spring.beans.Person; import com.learn.spring.beans.PersonList; import com.learn.spring.beans.PersonMap;public class Main {public static void main(String[] args) {Person person = (Person) ctx.getBean("person");System.out.println(person); } }?
總結(jié)
以上是生活随笔為你收集整理的依赖注入_引用其他的bean的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 依赖注入的细节_value子标签_特殊字
- 下一篇: 内部bean