1.Xml配置里的bean自动装配
</bean>
<!-- 自动装配 将当前实例中所有的对象属性 全部进行填充
byType对象属性所在的类 在容器中 只能拥有一个实例
多个实例是相对的 如果b中是个集合可以装配多个A
byName根据当前对象属性的名称来查找对应的实例
-->
<bean id="b" class="cn.et.lesson01.autowire.B" autowire="byType" scope="prototype">
</bean>
2. 使用外部属性文件
在配置文件里配置 Bean 时, 有时需要在Bean 的配置里混入系统部署的细节信息
PropertyPlaceholderConfigurer 从属性文件里加载属性, 并使用这些属性来替换变量.
配置context:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
Bean与context读取文件资源的优先级:
Bean读取资源文件:优先读取配置文件
Context命名空间读取资源文件:优先读取系统文件
读取配置文件的两种方法:
配置文件
url=jdbc:mysql://localhost:3306/shop
driverClass=com.mysql.jdbc.Driver
userName1=root
password=123
读取:
<!-- ${username}是个关键字 默认获取操作系统的用户名Admimistrator-->
方法1
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:cn/et/lesson02/jdbc/jdbcmysql.properties"></property> </bean>
方法2 <context:property-placeholder location="classpath:cn/et/lesson02/jdbc/jdbcmysql.properties" /> <bean id="dataSouce" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url" value="${url}"></property> <property name="username" value="${userName1}"></property> <property name="password" value="${password}"></property> <property name="driverClassName" value="${driverClass}"></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSouce"></property> </bean>