💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
正如上一节[1.4.1依赖注入](1.4.1依赖注入.md)提到的,你可以通过`<property/>`和`<constructor-arg/>`元素注入成员属性和构造参数或者直接使用简单值完成依赖的配置。 [1.4.1.依赖注入](1.4.1.依赖注入.md) ### **简单值(基本类型、字符串等等)** `<property/>`元素的`value`属性可以为成员属性或者构造参数指定一个可读性高的字符串值,并且Spring的类型转换服务([3.5.4.ConversionService API](3.5.4.ConversionServiceAPI.md))可以将String类型的数据转换为属性或者参数实际需要的类型。 ~~~ <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- 通过调用 setDriverClassName(String) 来设置属性 --> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mydb"/> <property name="username" value="root"/> <property name="password" value="masterkaoli"/> </bean> ~~~ 下面的样例使用了`p-namespace`来简化XML配置。 ~~~ <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"> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/mydb" p:username="root" p:password="masterkaoli"/> </beans> ~~~ 上面的例子显得更加简洁,但是单词拼写错误在运行时才发现而不是编写代码时,除非使用[IntelliJ IDEA](http://www.jetbrains.com/idea/) 或者[Spring Tool Suite](https://spring.io/tools/sts) (STS)等支持属性自动完成的IDE,并且使用这样的IDE是一种很棒的体验。 你也可以像这样配置`java.util.Properties`实例: ~~~ <bean id="mappings" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="properties"> <value> jdbc.driver.className=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mydb </value> </property> </bean> ~~~ Spring容器通过`PropertyEditor`将`<value/>`元素内的文本转换为`java.util.Properties`实例。这种方式简单快捷,所以Spring团队更喜欢`<value/>`元素而不是`value`属性。 ##### `<idref/>`元素 此元素是一种通过其他Bean的id值来引用Bean的方式,可以使用在`<constructor-arg/>`或者`<property/>`元素中,并且拥有错误校验的功能。 ~~~ <bean id="theTargetBean" class="..."/> <bean id="theClientBean" class="..."> <property name="targetName"> <idref bean="theTargetBean"/> </property> </bean> ~~~ 上面的配置与下面的配置完全等价(运行时): ~~~ <bean id="theTargetBean" class="..." /> <bean id="client" class="..."> <property name="targetName" value="theTargetBean"/> </bean> ~~~ 第一种形式的配置要优于第二种,因为`<idref/>`元素使得容器会在部署时就验证引用的Bean是否真实存在。在第二例子中,`targetName`的值不会被验证,拼写错误只能在`client` Bean被实例化时才出现(很有可能出现严重错误)。如果`client` Bean是原型模式的,拼写错误和异常结果可能会在容器发布很久之后才被发现。