Spring入门实例-beanfactorypostprocessor
实例:
配置文件:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="configBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>com/myspring/beanfacotrypostprocessor/hello.properties</value> </property> </bean> <!-- <bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer"> <property name="location"> <value>com/myspring/beanfacotrypostprocessor/hello.properties</value> </property> </bean> --> <bean id="helloBean" class="com.myspring.beanfacotrypostprocessor.PostBean"> <property name="dbname"> <value>oracle</value> </property> </bean> <bean id="helloBean2" class="com.myspring.beanfacotrypostprocessor.PostBean"> <property name="dbname"> <value>${db_mysql}</value> </property> </bean> </beans>
在properties文件中,可以使用覆盖PropertyOverrideConfigurer,直接写helloBean.dbname="mysql"覆盖原值
或是使用PropertyPlaceholderConfigurer使用${db_mysql},db_mysql="mysql"赋值dbname属性
properties文件:
helloBean.dbname=mysql db_mysql=sqlserver
bean:
public class PostBean { private String dbname; public void setDbname(String dbname) { this.dbname = dbname; } public String getDbname() { return dbname; } }
测试main:
public class TestPropertyPost { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("com/myspring/beanfacotrypostprocessor/propertypostxml.xml"); PostBean pb = (PostBean) context.getBean("helloBean2"); System.out.println(pb.getDbname()); } }