注入复杂类型
数组、集合(List、Set)、Map、Properties 。
<bean id="bean" class="com.example.spring.di.complex.Bean">
<constructor-arg name="prop1">
<!--
对于复杂类型来说,必须通过constructor-arg的子标签来配置。
-->
<array>
<value>1</value>
<value>2</value>
</array>
</constructor-arg>
<constructor-arg name="prop2">
<list>
<value>2</value>
<value>3</value>
</list>
</constructor-arg>
<constructor-arg name="prop3">
<set>
<value>30</value>
<value>20</value>
<value>30</value> <!--set会自动去重-->
</set>
</constructor-arg>
<constructor-arg name="prop4">
<map>
<entry key="key1" value="value1"/>
<entry key="key2" value="value2"/>
</map>
</constructor-arg>
<constructor-arg name="prop5">
<props>
<prop key="driverClass">com.mysql.jdbc.Driver</prop>
</props>
</constructor-arg>
</bean>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4coRNiY0-1600244803746)(imges/image-20200826100722091.png)]
外部属性值的注入
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4GUpMyZl-1600244837070)(imges/image-20200826101051469.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PrAbJ5IY-1600244837072)(imges/image-20200826101334748.png)]
<!--
要想在Spring的配置文件中,注入外部properties配置文件中的内容:
方式1:
定义一个Spring提供的特殊的类作为bean,类是 PropertyPlaceholderConfigurer
它的使用方式,是通过设置它的 Location 或 Locations 属性,指定 properties 文件的位置。
PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
configurer.setLocation(位置);
org.springframework.core.io.Resource 类型
此接口是Spring中对资源文件的抽象,类路径下的资源用: ClassPathResource 类来表示
另外: Spring配置文件中,对资源的表达做了简化。
原来的 Resource类型,当是类路径下的资源时(本质上对应ClassPathResource),可以直接使用字符串来表示
格式:
`classpath:` 做为前缀 + 资源的位置
classpath:com/example/spring/di/complex/db-config.properties
Spring底层会自动将此字符串转换为一个 ClassPathResource 对象。
方式2:
Spring 对这个场景也做了简化配置。
<context:property-placeholder>
其实底层,Spring看到这个标签的时候,也会注册PropertyPlaceholderConfigurer类型
最后:
咱们在Spring配置中,就可以直接嵌入 `${properties配置文件中的key}` 的形式来插值
-->
<!-- <bean name="configResource" class="org.springframework.core.io.ClassPathResource" c:path="com/example/spring/di/complex/db-config.properties">-->
<!-- </bean>-->
<!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">-->
<!-- <property name="location" value="classpath:com/example/spring/di/complex/db-config.properties"/>-->
<!-- </bean>-->
<context:property-placeholder location="classpath:com/example/spring/di/complex/db-config.properties"/>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lWD59Vqu-1600244837076)(imges/image-20200826103714726.png)]