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. 牛客多校第五场 H subsequence 2 拓扑排序

    题意: 给你长度最长为1000的字符串,这个字符串中最多有10种字母,每次给你两种字母,输出这两种字母在字符串中的相对位置,问你这个字符串原本是什么样子,如果不存在则输出-1 题解: 把整个字符串看作 ...

  2. fatal error U1087: cannot have : and :: dependents for same target Stop.

    转自VC错误:http://www.vcerror.com/?p=72 问题描述: 完成后编译,发现有错误  D:\WinDDK\7600.16385.1\bin\makefile.new(7117) ...

  3. 在VMare Workstation 10中安装Ubuntu

    (1) 下面就是成功配置了VM的环境 (2)在弹出的settings里,点击"CD/DVD(IDE)",然后在右侧点击"Use ISO image file", ...

  4. java 测试时 程序的 运行时间

    检测一个JAVA程序的运行时间方法:long startTime = System.currentTimeMillis();//获取当前时间//doSomeThing();   //要运行的java程 ...

  5. DOM节点克隆

    var newDiv = red.cloneNode();document.body.appendChild(newDiv);注意:1.默认只克隆元素本身:设置参数为true,进行深度克隆,可以克隆元 ...

  6. 平衡树模板【splay的实现】

    [平衡树splay实现] 无注释代码 #include<bits/stdc++.h> using namespace std; typedef long long LL; ,MAXN=1e ...

  7. QQ交流群

  8. RabbitMQ代码操作之发消息和序列化机制

    几个自动配置类: 1.RabbitAutoConfiguration2.有自动配置了连接工厂 ConnectionFactory3.RabbitProperties 封装了RabbitMQ的配置4.R ...

  9. Less适配移动端rem

    @ue-width: 750; /* 设计图的宽度 */ .px2rem(@px) { @remValue: @px/@ue-width*10; @pxToRem: ~"@{remValue ...

  10. js图片预加载实现!

    var myImage = (function(){ var imgNode = document.createElement( 'img' ); document.body.appendChild( ...