Spring Boot 环境变量读取 和 属性对象的绑定
网上看到的一些方法,结合我看到的 和我们现在使用的。整理成此文;
第一种方法
参见catoop的博客之 Spring Boot 环境变量读取 和 属性对象的绑定(尊重原创)
第二种方法
- class不用继承任何东西,只需在类中添加属性
@Inject
private Environment env;
- 调用
OTHER_DIR = env.getProperty("converter.sourcedir");
converter.sourcedir是yml中的配置,如下
converter:
sourcedir: /a/b/c/d
继续深究,Environment的源码:
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.env;
/**
* Interface representing the environment in which the current application is running.
* Models two key aspects of the application environment: <em>profiles</em> and
* <em>properties</em>. Methods related to property access are exposed via the
* {@link PropertyResolver} superinterface.
*
* <p>A <em>profile</em> is a named, logical group of bean definitions to be registered
* with the container only if the given profile is <em>active</em>. Beans may be assigned
* to a profile whether defined in XML or via annotations; see the spring-beans 3.1 schema
* or the {@link org.springframework.context.annotation.Profile @Profile} annotation for
* syntax details. The role of the {@code Environment} object with relation to profiles is
* in determining which profiles (if any) are currently {@linkplain #getActiveProfiles
* active}, and which profiles (if any) should be {@linkplain #getDefaultProfiles active
* by default}.
*
* <p><em>Properties</em> play an important role in almost all applications, and may
* originate from a variety of sources: properties files, JVM system properties, system
* environment variables, JNDI, servlet context parameters, ad-hoc Properties objects,
* Maps, and so on. The role of the environment object with relation to properties is to
* provide the user with a convenient service interface for configuring property sources
* and resolving properties from them.
*
* <p>Beans managed within an {@code ApplicationContext} may register to be {@link
* org.springframework.context.EnvironmentAware EnvironmentAware} or {@code @Inject} the
* {@code Environment} in order to query profile state or resolve properties directly.
*
* <p>In most cases, however, application-level beans should not need to interact with the
* {@code Environment} directly but instead may have to have {@code ${...}} property
* values replaced by a property placeholder configurer such as
* {@link org.springframework.context.support.PropertySourcesPlaceholderConfigurer
* PropertySourcesPlaceholderConfigurer}, which itself is {@code EnvironmentAware} and
* as of Spring 3.1 is registered by default when using
* {@code <context:property-placeholder/>}.
*
* <p>Configuration of the environment object must be done through the
* {@code ConfigurableEnvironment} interface, returned from all
* {@code AbstractApplicationContext} subclass {@code getEnvironment()} methods. See
* {@link ConfigurableEnvironment} Javadoc for usage examples demonstrating manipulation
* of property sources prior to application context {@code refresh()}.
*
* @author Chris Beams
* @since 3.1
* @see PropertyResolver
* @see EnvironmentCapable
* @see ConfigurableEnvironment
* @see AbstractEnvironment
* @see StandardEnvironment
* @see org.springframework.context.EnvironmentAware
* @see org.springframework.context.ConfigurableApplicationContext#getEnvironment
* @see org.springframework.context.ConfigurableApplicationContext#setEnvironment
* @see org.springframework.context.support.AbstractApplicationContext#createEnvironment
*/
public interface Environment extends PropertyResolver {
/**
* Return the set of profiles explicitly made active for this environment. Profiles
* are used for creating logical groupings of bean definitions to be registered
* conditionally, for example based on deployment environment. Profiles can be
* activated by setting {@linkplain AbstractEnvironment#ACTIVE_PROFILES_PROPERTY_NAME
* "spring.profiles.active"} as a system property or by calling
* {@link ConfigurableEnvironment#setActiveProfiles(String...)}.
* <p>If no profiles have explicitly been specified as active, then any {@linkplain
* #getDefaultProfiles() default profiles} will automatically be activated.
* @see #getDefaultProfiles
* @see ConfigurableEnvironment#setActiveProfiles
* @see AbstractEnvironment#ACTIVE_PROFILES_PROPERTY_NAME
*/
String[] getActiveProfiles();
/**
* Return the set of profiles to be active by default when no active profiles have
* been set explicitly.
* @see #getActiveProfiles
* @see ConfigurableEnvironment#setDefaultProfiles
* @see AbstractEnvironment#DEFAULT_PROFILES_PROPERTY_NAME
*/
String[] getDefaultProfiles();
/**
* Return whether one or more of the given profiles is active or, in the case of no
* explicit active profiles, whether one or more of the given profiles is included in
* the set of default profiles. If a profile begins with '!' the logic is inverted,
* i.e. the method will return true if the given profile is <em>not</em> active.
* For example, <pre class="code">env.acceptsProfiles("p1", "!p2")</pre> will
* return {@code true} if profile 'p1' is active or 'p2' is not active.
* @throws IllegalArgumentException if called with zero arguments
* or if any profile is {@code null}, empty or whitespace-only
* @see #getActiveProfiles
* @see #getDefaultProfiles
*/
boolean acceptsProfiles(String... profiles);
}
鉴于注释太多,抽出其中核心代码:
package org.springframework.core.env;
public interface Environment extends PropertyResolver {
String[] getActiveProfiles();
String[] getDefaultProfiles();
boolean acceptsProfiles(String... profiles);
}
可以看到Environment 又extends PropertyResolver
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.env;
/**
* Interface for resolving properties against any underlying source.
*
* @author Chris Beams
* @since 3.1
* @see Environment
* @see PropertySourcesPropertyResolver
*/
public interface PropertyResolver {
/**
* Return whether the given property key is available for resolution, i.e.,
* the value for the given key is not {@code null}.
*/
boolean containsProperty(String key);
/**
* Return the property value associated with the given key, or {@code null}
* if the key cannot be resolved.
* @param key the property name to resolve
* @see #getProperty(String, String)
* @see #getProperty(String, Class)
* @see #getRequiredProperty(String)
*/
String getProperty(String key);
/**
* Return the property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
* @param defaultValue the default value to return if no value is found
* @see #getRequiredProperty(String)
* @see #getProperty(String, Class)
*/
String getProperty(String key, String defaultValue);
/**
* Return the property value associated with the given key, or {@code null}
* if the key cannot be resolved.
* @param key the property name to resolve
* @param targetType the expected type of the property value
* @see #getRequiredProperty(String, Class)
*/
<T> T getProperty(String key, Class<T> targetType);
/**
* Return the property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
* @param key the property name to resolve
* @param targetType the expected type of the property value
* @param defaultValue the default value to return if no value is found
* @see #getRequiredProperty(String, Class)
*/
<T> T getProperty(String key, Class<T> targetType, T defaultValue);
/**
* Convert the property value associated with the given key to a {@code Class}
* of type {@code T} or {@code null} if the key cannot be resolved.
* @throws org.springframework.core.convert.ConversionException if class specified
* by property value cannot be found or loaded or if targetType is not assignable
* from class specified by property value
* @see #getProperty(String, Class)
*/
<T> Class<T> getPropertyAsClass(String key, Class<T> targetType);
/**
* Return the property value associated with the given key (never {@code null}).
* @throws IllegalStateException if the key cannot be resolved
* @see #getRequiredProperty(String, Class)
*/
String getRequiredProperty(String key) throws IllegalStateException;
/**
* Return the property value associated with the given key, converted to the given
* targetType (never {@code null}).
* @throws IllegalStateException if the given key cannot be resolved
*/
<T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException;
/**
* Resolve ${...} placeholders in the given text, replacing them with corresponding
* property values as resolved by {@link #getProperty}. Unresolvable placeholders with
* no default value are ignored and passed through unchanged.
* @param text the String to resolve
* @return the resolved String (never {@code null})
* @throws IllegalArgumentException if given text is {@code null}
* @see #resolveRequiredPlaceholders
* @see org.springframework.util.SystemPropertyUtils#resolvePlaceholders(String)
*/
String resolvePlaceholders(String text);
/**
* Resolve ${...} placeholders in the given text, replacing them with corresponding
* property values as resolved by {@link #getProperty}. Unresolvable placeholders with
* no default value will cause an IllegalArgumentException to be thrown.
* @return the resolved String (never {@code null})
* @throws IllegalArgumentException if given text is {@code null}
* or if any placeholders are unresolvable
* @see org.springframework.util.SystemPropertyUtils#resolvePlaceholders(String, boolean)
*/
String resolveRequiredPlaceholders(String text) throws IllegalArgumentException;
}
第三种方法(最简单)
@Value("${a.b.c.d}")
private String testValue;
a.b.c.d 是配置文件中的
就这样简单~~~
Spring Boot 环境变量读取 和 属性对象的绑定的更多相关文章
- 十五、Spring Boot 环境变量读取 和 属性对象的绑定
凡是被spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,获取到系统环境变量和application配置文件中的变量. 如: @ ...
- 24. Spring Boot环境变量读取和属性对象的绑定【从零开始学Spring Boot】
转:http://blog.csdn.net/linxingliang/article/details/52069509 凡是被spring管理的类,实现接口EnvironmentAware 重写方法 ...
- (24)Spring Boot环境变量读取和属性对象的绑定【从零开始学Spring Boot】
凡是被Spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,获取到系统环境变量和application配置文件中的变量. com. ...
- Spring Boot配置,读取配置文件
Spring Boot配置,读取配置文件 一.配置Spring Boot 1.1 服务器配置 1.2 使用其他Web服务器 1.3 配置启动信息 1.4 配置浏览器显示ico 1.5 Yaml语法 1 ...
- Spring boot接受json赋值给java对象
Spring boot接受json赋值给java对象 新建 模板 小书匠 前言 写这个东西,一方面是我自己在做项目的时候,对json的使用还不是十分的熟悉,对spring boot的使用也不是很熟悉, ...
- spring boot 环境配置(profile)切换
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- bash环境变量读取顺序
bash环境变量读取顺序: 交互式登录的用户: /etc/profile --> /etc/profile.d/*.sh --> ~/.bash_profile --> ~/.bas ...
- 在spring boot环境中使用fastjson + redis的高速缓存技术
因为项目需求,需要在spring boot环境中使用redis作数据缓存.之前的解决方案是参考的http://wiselyman.iteye.com/blog/2184884,具体使用的是Jackso ...
- Service Fabric service 根据环境变量读取配置文件
前言 一个服务或者产品,往往需要三个环境:一个开发环境(Development),一个测试环境(Staging),一个生产环境(Production), 这就不可避免的需要多个配置文件来匹配相应的环境 ...
随机推荐
- BZOJ 1061 志愿者招募(最小费用最大流)
题目链接:http://61.187.179.132/JudgeOnline/problem.php?id=1061 题意:申奥成功后,布布经过不懈努力,终于 成为奥组委下属公司人力资源部门的主管.布 ...
- Beaglebone Black–GPIO 开关 LED(三极管与继电器实验)
上一篇,用 GPIO 直接供电给 LED,用高低电平作开关,不靠谱.GPIO 是信号用的,不是当电源用的.而且,一个 GPIO 只能给可怜的 5mA 左右,取多了会烧(我没烧过不知道是不是真的会烧,但 ...
- linux的计划任务crontab
crontab(全称cron table计划任务列表)是一个用于周期性被执行的任的工具. 相关指令: usage: crontab [-u user] file crontab [ -u user ...
- Codeforces Round #377 (Div. 2) C. Sanatorium 水题
C. Sanatorium time limit per test 1 second memory limit per test 256 megabytes input standard input ...
- RARP
ARP的工作原理如下:1. 首先,每台主机都会在自己的ARP缓冲区 (ARP Cache)中建立一个 ARP列表,以表示IP地址和MAC地址的对应关系.2. 当源主机需要将一个数据包要发送到目的主机时 ...
- chubu
python解释型语言,不需要编译成机器认可的二进制码,而是直接从源代码运行程序. python是基于c语言开发的. python很容易嵌入到其他语言. 中文注释,必须在前边加上注释说明 : #_*_ ...
- Runtime.getRuntime().addShutdownHook
Runtime.getRuntime().addShutdownHook(shutdownHook); 这个方法的含义说明: 这个方法的意思就是在jvm中增加一个关闭的钩子,当jvm关闭的时候,会 ...
- Win7_关闭休眠文件hiberfil.sys
1. C盘根目录下 hiberfil.sys 占用好几G空间,直接删 删不掉,也不推荐直接删. 2. 2.1.命令窗口中输入 powercfg -h off,即可关闭休眠功能,同时 Hiberfil. ...
- UIButton、UIImageView、UILabel的选择
UIButton特点既能显示文字,又能显示图片(能显示2张图片,背景图片.内容图片)长按高亮的时候可以切换图片\文字直接通过addTarget...方法监听点击 UIImageView能显示图片,不能 ...
- JAVA调用C语言写的SO文件
JAVA调用C语言写的SO文件 因为工作需要写一份SO文件,作为手机硬件IC读卡和APK交互的桥梁,也就是中间件,看了网上有说到JNI接口技术实现,这里转载了一个实例 // 用JNI实现 // 实例: ...