spring学习(5)
bean配置
启用注解
<context:annotation-config/>
使用spring的特殊bean
对bean
BeanPostProcessor
spring本身提供的特殊bean
1.实现了BeanPostProcessor的后置处理器
2.PropertyPlaceholderConfigurer.
分散配置(有两种方式引入文件)
使用spring的特殊bean,完成分散配置。
beans.xml
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd "> <!-- 引入我们的db. --> <context:property-placeholder location="classpath:com/hsp/dispatch/db.properties,classpath:com/hsp/dispatch/db2.properties"/> <bean id="dbutil" class="com.hsp.dispatch.DBUtil"> <property name="name" value="${name}"/> <property name="drivername" value="${drivername}"/> <property name="url" value="${url}"/> <property name="pwd" value="${pwd}"/> </bean> <bean id="dbutil2" class="com.hsp.dispatch.DBUtil"> <property name="name" value="${name}"/> <property name="drivername" value="${drivername}"/> <property name="url" value="${url}"/> <property name="pwd" value="${pwd}"/> </bean> </beans>
说明:当通过context:property-placeholder引入属性文件的时候,有多个需要使用,号间隔。
package com.hsp.dispatch; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App1 { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("com/hsp/dispatch/beans.xml"); DBUtil dbUtil = (DBUtil)ac.getBean("dbutil2"); System.out.println(dbUtil.getDrivername()); System.out.println(dbUtil.getName()); System.out.println(dbUtil.getUrl()); System.out.println(dbUtil.getPwd()); } }
db2.properties
name=root2 drivername=oracle:jdbc:driverDriver2 url=jdbc:oracle:thin:@127.0.0.1:1521:hsp2 pwd=tiger2
使用占位符变量代替bean装配文件中的硬编码配置。占位符采用${variable}形式。