一、Spring 读取配置文件的实现方式

Spring 框架可以通过多种方式读取配置文件,具体实现方式有:

1、使用 ClassPathXmlApplicationContext 读取 XML 文件;
2、使用 PropertyPlaceholderConfigurer 读取 properties 文件;
3、使用 XmlBeanFactory 读取 XML 文件;
4、使用 Resource 读取文件;
5、使用 Spring 的 @Value 注解读取配置文件;
6、使用 Spring 的 Environment 读取配置文件。

二、ClassPathXmlApplicationContext 读取 XML 文件

ClassPathXmlApplicationContext 是 Spring 框架中提供的用于读取 XML 文件的类,可以用来读取配置文件,它的使用方法如下:

12345678ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BeanFactory beanFactory = (BeanFactory) context;
DataSource dataSource = (DataSource) beanFactory.getBean("dataSource");
String driverClassName = dataSource.getDriverClassName();
String url = dataSource.getUrl();
String userName = dataSource.getUsername();
String password = dataSource.getPassword();
context.close();
Java

上述代码中,第一行创建 ClassPathXmlApplicationContext 实例,第二行使用该实例获取 BeanFactory 实例,第三行使用 BeanFactory 实例获取 DataSource 实例,第四行获取数据库连接驱动类名,第五行获取数据库连接 URL,第六行获取数据库用户名,第七行获取数据库密码,第八行关闭 ClassPathXmlApplicationContext 实例。

三、PropertyPlaceholderConfigurer 读取 properties 文件

PropertyPlaceholderConfigurer 是 Spring 框架提供的用于读取 properties 文件的类,可以用来读取配置文件,它的使用方法如下:

1234567PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
configurer.setLocation(new ClassPathResource("jdbc.properties"));
configurer.setIgnoreUnresolvablePlaceholders(true);
configurer.setOrder(1);
configurer.postProcessBeanFactory(beanFactory);
String driverClassName = beanFactory.getBean("driverClassName", String.class);
String url = beanFactory.getBean("url", String.class);
String userName = beanFactory.getBean("userName", String.class);
String password = beanFactory.getBean("password", String.class);
Java

上述代码中,第一行创建 PropertyPlaceholderConfigurer 实例,第二行设置要读取的 properties 文件,第三行设置是否忽略未解析的占位符,第四行设置 PropertyPlaceholderConfigurer 的处理顺序,第五行调用 postProcessBeanFactory 方法,第六行获取数据库连接驱动类名,第七行获取数据库连接 URL,第八行获取数据库用户名,第九行获取数据库密码。