spring中的配置文件有两种:

  • 以XML结尾的spring配置文件
  • 以properties结尾的属性配置文件

在spring中有两种方式加载这两种文件:

  • 通过注解+java配置的方式
  • 通过XML的方式

详细配置且看下文:

一、加载spring配置文件*.xml

假设有一个关于数据源的配置文件spring-database.xml,它的配置内容如下:

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5433/postgres" />
<property name="username" value="postgres" />
<property name="password" value="postgres" />
</bean>
</beans>

1⃣️通过注解+java配置方式

第一步:通过注解+配置方式时需要创建一个配置类AppConfig.java

 @ComponentScan(basePackages= {"com.hyc.config"})
@ImportResource({"classpath:spring-database.xml"})
public class AppConfig { }

上面的配置中:

1⃣️使用注解@ImportResource引入配置文件,可以是多个;

2⃣️通过注解@ComponentScan定义spring扫描的包(因为下面有个bean的类我定义在这个包下,所以这里加上这个扫描路径)

第二步:写一个获取数据库连接的类

 package com.hyc.config;
/*
* 通过注解+配置的方式加载spring配置文件
*/ import java.sql.Connection;
import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; @Component("dbba")
public class DatasourceByAnnotation { @Autowired
DataSource dataSource = null; // 获取数据库连接
public Connection getConnection() {
Connection conn = null;
try {
conn = dataSource.getConnection();
if (null != conn) {
System.out.println("获取数据库连接成功");
} else {
System.out.println("获取数据库连接失败");
}
} catch (SQLException e) {
e.printStackTrace();
} return conn;
}
}

上面代码中加粗部分:

  • 此类所在的包,需要告知spring在哪个包下扫描,如果配置文件类和这个类在同意包下,则不需要配置
  • @Component注解:定义此bean的名称,这样可以通过getBean方法获取到

第三步:编写测试方法

 public class GetDatasourceByConfigTest {

     @Test
public void testGetByConfig() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
DatasourceByAnnotation dba = (DatasourceByAnnotation) context.getBean("dbba");
dba.getConnection();
}
}

这里就是使用注解+java配置方式获取bean,调用其方法,测试结果:

配置成功,有些书上说这个地方获取DataSource时可以使用自动注解,我试了一下是不可以的,其实按理说也是不行的,因为DataSource是第三方包中的类,我们无法对它进行修改,如果使用自动注解获取,必定要给他增加@Component注解进行定义,所以这种方式只能通过配置获取。

2⃣️通过XML方式

使用XML的方式,假设我要在spring-bean.xml中引入spring-database.xml文件,只需要在spring-bean.xml中加入一句代码即可:

<import resource="spring-database.xml"/>

这样就可以当作spring-bean.xml文件进行使用了,其实这种方式主要是为了将不同业务的配置通过文件区分开来,不要是spring-bean.xml文件变得很庞大复杂,具体实现不做介绍。

二、加载属性配置文件*.properties

依然是数据源的配置文件,只不过这次将其写在属性配置文件db.properties中,配置如下:

 db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://localhost:5433/postgres
db.username=postgresql
db.pwd=postgresql

1⃣️通过注解+java配置方式

第一步:通过注解+配置方式时需要创建一个配置类AppConfig.java

 @Configuration
@PropertySource(value = { "classpath:db.properties" }, ignoreResourceNotFound = true)
public class AppConfig { }

上面的配置中:

  • 使用注解@PropertySource引入配置文件,可以是多个;
  • 通过注解@Configuration不能缺失,否则将找不到这个配置

第二步:测试

 @Test
public void testGetPropByConfig() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
String url = context.getEnvironment().getProperty("db.url");
System.out.println(url);
}

获取属性文件中的数据库连接URL,看能不能获取到,测试结果如下:

可见获取成功。

上面的测试中是通过环境来获取对应的配置属性,但如果这样在spring中是没有解析属性占位符的能力,spring推荐使用一个属性文件解析类PropertySourcePlaceholderConfigurer,使用它就意味允许spring解析对应的属性文件,并通过占位符去引用对应的配置。

修改上述的配置类为如下:

 @Configuration
@ComponentScan(basePackages = { "com.hyc.config" })
@PropertySource(value = { "classpath:db.properties" }, ignoreResourceNotFound = true)
public class AppConfig { /**
* 定义一个PropertyPlaceholderConfigurer类的bean,它的作用是为了让spring能解析占位符
* @return
*/
@Bean
public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertyPlaceholderConfigurer();
} }

有了上面的配置,就可以通过占位符引用属性值了,如下:

 @Component("dsb")
public class DataSourceBean { @Value("${db.driver}")
private String driver = null; @Value("${db.url}")
private String url = null; @Value("${db.username}")
private String userName = null; @Value("${db.pwd}")
private String pwd = null; public void getDataSourceUrl() {
System.out.println(url);
} }

编写测试类:

 @Test
public void testGetPropByConfig1() {
@SuppressWarnings("resource")
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
DataSourceBean ds = (DataSourceBean) context.getBean("dsb");
ds.getDataSourceUrl();
}

这样就能获取到了

2⃣️通过XML方式

XML方式的配置如下:

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 配置单个属性文件 -->
<context:property-placeholder
ignore-resource-not-found="false" location="classpath*:db.properties" />
<!-- 配置多个属性文件 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array>
<value>classpath:db.properties</value>
<value>classpath:log4j.properties</value>
</array>
</property>
<property name="ignoreResourceNotFound" value="false"></property>
</bean>
</beans>

如上,可以配置多个,也可以配置一个,这样以来,就能在spring的配置文件中通过占位符引用属性了。

装配SpringBean(六)--配置文件加载方式的更多相关文章

  1. Spring之配置文件加载方式

    spring在org.springframework.core.io包中提供了多种配置文件加载方式.无论是XML.URL还是文件,都有很好的支持.比如基于URL的UrlResource.基于输入流的I ...

  2. log4j配置文件加载方式

    使用背景: apache的log4j是一个功能强大的日志文件,当我们使用eclipse等IDE在项目中配置log4j的时候,需要知道我们的配置文件的加载方式以及如何被加载的. 加载方式: (1).自动 ...

  3. Spring Cloud配置文件加载优先级简述

    Spring Cloud中配置文件的加载机制与其它的Spring Boot应用存在不一样的地方:如它引入了bootstrap.properties的配置文件,同时也支持从配置中心中加载配置文件等:本文 ...

  4. Spring使用环境变量控制配置文件加载

    项目中需要用到很多配置文件,不同环境的配置文件是不一样的,因此如果只用一个配置文件,势必会造成配置文件混乱,这里提供一种利用环境变量控制配置文件加载的方法,如下: 一.配置环境变量 如果是window ...

  5. log4j加载方式导致的bae和sae部署异常

    这2天改在bae上部署代码,为了便于程序的功能测试,引入了log4j日志,但是问题来了..测试程序采用的是spring3.2.8框架搭建,web.xml引入日志代码为: <context-par ...

  6. javascript 的加载方式

    本文总结一下浏览器在 javascript 的加载方式. 关键词:异步加载(async loading),延迟加载(lazy loading),延迟执行(lazy execution),async 属 ...

  7. asp.netcore 深入了解配置文件加载过程

    前言     配置文件中程序运行中,担当着不可或缺的角色:通常情况下,使用 visual studio 进行创建项目过程中,项目配置文件会自动生成在项目根目录下,如 appsettings.json, ...

  8. bash 的配置文件加载顺序

    bash配置文件的加载顺序和登陆方式有关,下面先介绍下登陆方式. 1 登陆方式有2种 登陆式SHELL: su - oracle    su -l oracle 正常从终端登陆 非登录式SHELL: ...

  9. springboot的yaml基础语法与取值,配置类,配置文件加载优先级

    1.基本语法k:(空格)v:表示一对键值对(一个空格必须有):以空格的缩进来控制层级关系:只要是左对齐的一列数据,都是同一个层级的属性和值也是大小写敏感: server: port: 8081 pat ...

随机推荐

  1. pycharm同时使用python2.7和python3.5设置方法

    pycharm同时使用python2.7和python3.5设置方法 - CSDN博客https://blog.csdn.net/qwerty200696/article/details/530159 ...

  2. git -- 项目开发最常用操作记录

    官方Git - Book https://git-scm.com/book/zh/v2 ------------------------------git配置以及公钥生成--------------- ...

  3. 开发笔记-19/10/28 -SpringBoot @Value 获取配置参数

    1. 在application.properties 定义参数 role.taskEvent :参数名称 4:值 ## ---------------------任务角色--------------- ...

  4. 第五周课堂笔记1th

    可迭代对象   Isinstance  判断一个对象是否属于某种类型 接受两个参数 迭代器 以下数据类型都没迭代器: 把没有迭代器的类型更改为有迭代器类型 用迭代器进行取值: 判断迭代器的方法: 3. ...

  5. appium + python 自动化调试手机时 UiAutomator exited unexpectedly with code 0, signal null

    放上appium报错图,appium在手机里安装了appium setting 和unlock 软件,输入法也被变成了appium input ,但是就是点不到目标软件,手机也可以被cmd  adb ...

  6. selenium基础(鼠标和键盘事件)

    selenium鼠标和键盘的操作事件 webdriver常见的几种操作方法 clear():清楚文本文字 send_keys(values):模拟按键输入,values是输入的内容 click():单 ...

  7. UBOOT把文件写入 NandFlash

    如果把一个传到内存中的文件写入到 Nand Flash 中, 如:新的 uboot.bin, zImage(内核), rootfs 等, 如果做呢?我们可以用 Nand Flash 命令来完成. 但是 ...

  8. (转)nginx配置location总结及rewrite规则写法

    注: rewrite 只能对域名后边的除去传递的参数外的字符串起作用,并且要写全域名后面的部分,如: http://i.com:9090/php/midou/admin.php/index/login ...

  9. 转载别人的ftp,觉得目录结构不错,学习

    开发简单的FTP:1. 用户登陆2. 上传/下载文件3. 不同用户家目录不同4. 查看当前目录下文件5. 充分使用面向对象知识 REDMAE 1 用户登陆 2 3 1.查看用户目录文件 4 2.上传文 ...

  10. bzoj2209 括号序列

    题意:给你一个括号序列.操作1:询问需要更改多少个括号使之匹配. 操作2:反转序列,左括号变成右括号. 操作3:翻转序列,倒置. 标程: #include<cstdio> #include ...