一、基于XML配置的方式

1.使用 PropertyPlaceholderConfigurer

- 在 applicationContext.xml 中配置:

<context:property-placeholder location="classpath*:db.properties"/>

或者:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath*:db.properties" ></property>
</bean>

- 之后就可以在代码中访问了:

@Component
public class TestComponent {
@Value("${jdbc.url}")
private String url;
}

2.使用 PropertiesFactoryBean

- 注册 bean

<bean id="dbProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath*:db.properties</value>
</list>
</property>
</bean>

- 使用

private String url;

@Resource(name = "dbProperties")
private Properties properties; @PostConstruct
public void init() {
url = properties.getProperty("jdbc.url");
}

3.使用 ResourceBundleMessageSource

- 注册 bean

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:db.properties</value>
</list>
</property>
</bean>

- 访问
可以使用如下方法来访问:

((ApplicationContext)context).getMessage("jdbc.url", null, null);

或者:

@Component
public class BeanTester {
@Autowired
private MessageSource messageSource; public void execute(){
String url = this.messageSource.getMessage("jdbc.url", null, null);
}
}

二、基于Java配置的方式

1.使用 PropertySource

1.1通过 Environment 来获取

@Configuration
// 另有 PropertySources 包含多个 @PropertySource 来配置多个配置文件
@PropertySource("classpath:db.properties")
public class PropertySource {
@Autowired
Environment env; public void execute() {
// 你可以按照如下的方式获取属性值
String url = this.env.getProperty("jdbc.url");
}
}

1.2通过 PropertySourcesPlaceholderConfigurer 来获取

@Configuration
@PropertySource("classpath:db.properties")
public class PropertySource {
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}

调用:

@Component
public class TestComponent {
@Value("${jdbc.url}")
private String url;
}

2.使用 PropertiesFactoryBean

- 注册 bean:

@Bean
public PropertiesFactoryBean propertiesFactoryBean() {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
// 可以配置多个配置文件,也可以使用setLocation值设置单个配置文件
Resource[] resources = new ClassPathResource[]{new ClassPathResource("db.properties")};
propertiesFactoryBean.setLocations(resources);
return propertiesFactoryBean;
}

- 使用:

@Component
public class BeanTester {
private String url; @Resource(name = "propertiesFactoryBean")
private Properties properties; @PostConstruct
public void init() {
// 取到jdbc.url对应的值并赋给了全局变量url
url = properties.getProperty("jdbc.url");
}
}

三、SpringBoot

1. application.xml (或.yml) 中有如下配置内容:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test

1.1 可以直接通过 @Value 注解获取:

@SpringBootApplication
@RestController
public class Applaction {
@Value("${spring.datasource.url}")
private String url;
}

1.2可以通过 Environment 来获取:

@SpringBootApplication
@RestController
public class Applaction {
@Autowired
private Environment env; public void test() {
// 获取配置文件中的属性
env.getProperty("spring.datasource.url");
}
}

2.如果是用户自定义的配置文件,我们可以使用 @ConfigurationProperties 注解来获取:

如你在resources/resources下有一个配置文件 author.properties:

author.name=EricChan
author.sex=male

我们可以通过 @ConfigurationProperties 来将 properties 属性和一个 Bean 及其属性关联,从而实现类型安全的配置:

@Getter
@Setter
@ToString
@Component
@PropertySource(value = "classpath:resources/author.properties", encoding = "UTF-8")
@ConfigurationProperties
public class Author { private String name; private String sex; }

之后我们就可以通过将该 Bean 注入到其他需要使用的地方就可以获取了,比如:

@RestController
public class TestController {
public final Author author; // 将该 bean 注入进来
public TestController(final Author author) {
this.author = author;
} public void test() {
System.out.println(author);
}
}

还有种通过注册监听器的方式可以来实现,实现 ApplicationListener<ApplicationStartedEvent>,但觉得该方式比较麻烦,不太实用,在这里暂不做介绍,有兴趣的可以自己百度谷歌就行了。

Spring读取配置文件的方式总结的更多相关文章

  1. 关于spring读取配置文件的两种方式

    很多时候我们把需要随时调整的参数需要放在配置文件中单独进行读取,这就是软编码,相对于硬编码,软编码可以避免频繁修改类文件,频繁编译,必要时只需要用文本编辑器打开配置文件更改参数就行.但没有使用框架之前 ...

  2. java web路径和spring读取配置文件

    此篇博客缘起:部署java web系统到阿里云服务器(ubuntu14.04)的时候,有以下两个问题 找不到自定义的property配置文件 上传图片的时候找不到路径 开发的时候是在windows上的 ...

  3. Spring 读取配置文件(一)

    注册 @Configuration 标识的类,spring 读取配置文件的时候该类会被自动装载 package cn.com.receive;import org.springframework.be ...

  4. python读取配置文件的方式

    python读取配置文件的方式 1.从config.ini中读取,后缀无所谓,文件名字也无所谓,不过config.ini是常用写法,所谓见名知意 config.ini内容: [global] ip = ...

  5. Spring 读取配置文件(二)

    Spring 读取配置文件并调用 bean package cn.com.test.receive; import org.springframework.beans.factory.annotati ...

  6. Java读取配置文件的方式

    Java读取配置文件的方式-笔记 1       取当前启动文件夹下的配置文件   一般来讲启动java程序的时候.在启动的文件夹下会有配置文件 classLoader.getResource(&qu ...

  7. Spring读取配置文件,获取bean的几种方式

    BeanFactory有很多实现类,通常使用 org.springframework.beans.factory.xml.XmlBeanFactory类.但对于大部分J2EE应用而言,推荐使 用App ...

  8. Spring读取配置文件的几种方式

    import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; imp ...

  9. Spring读取配置文件 @Value

    最近在学习Spring如何读取配置文件,记录下方便自己也方便别人: 大致分为两类吧,一种的思路是利用Spring的beanFactoryPostProcessor读取配置文件内容到内存中,也就是应用程 ...

随机推荐

  1. android线程及线程池

    众所周知,在UI系统中进行一些耗时操作,都会导致卡顿现象,因为一次刷新在16ms,如果当次操作过了这个时间,那么用户就能感觉到明显的卡顿,甚至引起ANR . 对于这种情况,一般都是再起一个线程,进行一 ...

  2. 前端h5开发发布ios

    1.首先要有一个html5+的软件HBuilder 2.整体完成然后就点发布,主要注意页面入口就是你的网页的入口 3.下载一个appuploader软件,无需mac本就可以方便的申请证书和描述(因为发 ...

  3. ylbtech-LanguageSamples-ExplicitInterface(显示接口)

    ylbtech-Microsoft-CSharpSamples:ylbtech-LanguageSamples-ExplicitInterface(显示接口) 1.A,示例(Sample) 返回顶部 ...

  4. 第五章:关于ESearch的应用

    ElasticSearch是一个开源的分布式搜索引擎,具备高可靠性,支持非常多的企业级搜索用例. 我在这里做一下简单介绍和整理: 首先.ES搜索引擎给予java开放使用之前必须安装java环境,使用j ...

  5. Leagal or Not —— 拓扑排序(王道)

    Problem Description ACM-DIY is a large QQ group where many excellent acmers get together. It is so h ...

  6. WRTNode(MT7620n)USB启动总结

    一.改动mt7620.dtsi,去掉默认的bootargs,kernel_menuconfig取消buildin的command line 二.kernel_menuconfig增加scsi驱动.US ...

  7. Java8 对多个异步任务进行流水线操作(笔记)

    现在我们要对商店商品进行折扣服务.每个折扣代码对应不同的折扣率,使用一个枚举变量Discount.Code来实现这一想法,具体代码如下所示. 以枚举类型定义的折扣代码 /** * 折扣服务api * ...

  8. 【翻译自mos文章】在Oracle单机数据库中定义database service

    来源于: Defining a Database Service with a Stand Alone Database (文档 ID 1260134.1) APPLIES TO: Oracle Da ...

  9. TP框架中模糊查询实现

    TP框架中模糊查询实现 $where['g.name'] = array('like','%'.$groupname.'%'); 表达式查询 上面的查询条件仅仅是一个简单的相等判断,可以使用查询表达式 ...

  10. CSDN下载频道于2014年7月17日改版,23日-24日系统维护

    尊敬的用户你们好: CSDN于2005年推出了下载服务,经过数年的发展,下载频道的用户已经为无数用户提供了帮助.分享500万的技术资源. 感谢用户们的资源共享精神,以及对CSDN下载频道的支持 下载频 ...