1. 程式人生 > >Spring屬性佔位符PropertyPlaceholderConfigurer的使用

Spring屬性佔位符PropertyPlaceholderConfigurer的使用

package com.zsw.config;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import
 org.springframework.jdbc.datasource.DriverManagerDataSource;

public class Config {
     public static void main(String[] args) {
         XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("src/com/zsw/config/conf.xml"));
         // 如果要在BeanFactory中使用,bean factory post-processor必須手動執行:
         PropertyPlaceholderConfigurer cfg = new
 PropertyPlaceholderConfigurer();
         cfg.setLocation(new FileSystemResource("src/com/zsw/config/jdbc.properties"));
         cfg.postProcessBeanFactory(factory);
         DriverManagerDataSource dataSource = (DriverManagerDataSource) factory.getBean("dataSource");
//         System.out.println(dataSource.getDriverClassName());

         
         
         System.out.println(dataSource.getUsername());
         // 注意,ApplicationContext能夠自動辨認和應用在其上部署的實現了BeanFactoryPostProcessor的bean。這就意味著,當使用ApplicationContext的時候應用PropertyPlaceholderConfigurer會非常的方便。由於這個原因,建議想要使用這個或者其他bean
         // factory postprocessor的使用者使用ApplicationContext代替BeanFactroy。
         ApplicationContext context = new ClassPathXmlApplicationContext("com/zsw/config/conf.xml");
         DriverManagerDataSource dataSource2 = (DriverManagerDataSource) context.getBean("dataSource");
         System.out.println(dataSource2.getUsername());
     }
 
}