- 使用 Spring Initializr 创建 Spring Boot 应用程序
- 在Spring Boot中配置Cassandra
- 在 Spring Boot 上配置 Tomcat 连接池
- 将Camel消息路由到嵌入WildFly的Artemis上
书接上文:
Spring读源码系列番外篇—02—PropertyResolver的结构体系剖析—上
和Environment相关的接口可以有那么多:
See Also:
PropertyResolver,
EnvironmentCapable,
ConfigurableEnvironment,
AbstractEnvironment,
StandardEnvironment,
org.springframework.context.EnvironmentAware,
org.springframework.context.ConfigurableApplicationContext.getEnvironment,
org.springframework.context.ConfigurableApplicationContext.setEnvironment,
org.springframework.context.support.AbstractApplicationContext.createEnvironment
可以看出该接口的发展潜力之大
个人认为这里英文注释有些讲的更加详细,所以我就不翻译了,不然翻译了反而读不懂了
public interface Environment extends PropertyResolver {
/**
获取当前激活的环境
*/
String[] getActiveProfiles();
/**
* Return the set of profiles to be active by default when no active profiles have
* been set explicitly.
*/
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 not active.
For example,
env.acceptsProfiles("p1", "!p2") will return true if profile 'p1' is active or 'p2' is not active.
*/
@Deprecated
boolean acceptsProfiles(String... profiles);
/**
Return whether the active profiles match the given Profiles predicate.
*/
boolean acceptsProfiles(Profiles profiles);
}
Environment顶层接口,主要暴露出来的接口主要功能是获取当前激活环境和默认环境,以及判断传入的环境是否被激活
public interface ConfigurableEnvironment extends Environment, ConfigurablePropertyResolver {
void setActiveProfiles(String... profiles);
void addActiveProfile(String profile);
void setDefaultProfiles(String... profiles);
/**
MutablePropertySources也是拥有一组属性源的集合
mutable是可变的意思,意味我们可以自己对返回的属性源进行CRUD
*/
MutablePropertySources getPropertySources();
//System.getProperty()
Map<String, Object> getSystemProperties();
//System.getenv()
Map<String, Object> getSystemEnvironment();
//合并两个环境
void merge(ConfigurableEnvironment parent);
}
可配置意味可以修改—通常里面会暴露出大量set接口
public abstract class AbstractEnvironment implements ConfigurableEnvironment {
public static final String IGNORE_GETENV_PROPERTY_NAME = "spring.getenv.ignore";
public static final String ACTIVE_PROFILES_PROPERTY_NAME = "spring.profiles.active";
public static final String DEFAULT_PROFILES_PROPERTY_NAME = "spring.profiles.default";
protected static final String RESERVED_DEFAULT_PROFILE_NAME = "default";
protected final Log logger = LogFactory.getLog(getClass());
private final Set<String> activeProfiles = new LinkedHashSet<>();
private final Set<String> defaultProfiles = new LinkedHashSet<>(getReservedDefaultProfiles());
//可变的属性源集合
private final MutablePropertySources propertySources;
//可配置的属性解析器
private final ConfigurablePropertyResolver propertyResolver;
public AbstractEnvironment() {
//如果构造函数没有传入一个属性源集合,那么默认创建一个空的可变的属性源集合
this(new MutablePropertySources());
}
protected AbstractEnvironment(MutablePropertySources propertySources) {
this.propertySources = propertySources;
//返回的是PropertySourcesPropertyResolver
this.propertyResolver = createPropertyResolver(propertySources);
//从名字看是自定义属性源---->说明我们可以尝试去自定义集合中的属性源
customizePropertySources(propertySources);
}
protected ConfigurablePropertyResolver createPropertyResolver(MutablePropertySources propertySources) {
//PropertySourcesPropertyResolver讲解过了----PropertyResolver下面的一个具体实现子类
//它负责从这些属性源中寻找key--->value
return new PropertySourcesPropertyResolver(propertySources);
}
protected final ConfigurablePropertyResolver getPropertyResolver() {
return this.propertyResolver;
}
//子类通过重新该方法完成对属性源的自定义修改操作---可以进行CRUD
protected void customizePropertySources(MutablePropertySources propertySources) {
}
protected Set<String> getReservedDefaultProfiles() {
return Collections.singleton(RESERVED_DEFAULT_PROFILE_NAME);
}
//---------------------------------------------------------------------
// Implementation of ConfigurableEnvironment interface
//---------------------------------------------------------------------
@Override
public String[] getActiveProfiles() {
return StringUtils.toStringArray(doGetActiveProfiles());
}
//获取激活的
protected Set<String> doGetActiveProfiles() {
synchronized (this.activeProfiles) {
//activeProfiles集合不为空,就直接返回该集合即可
if (this.activeProfiles.isEmpty()) {
//否则调用doGetActiveProfilesProperty获取激活的环境
String profiles = doGetActiveProfilesProperty();
if (StringUtils.hasText(profiles)) {
//缓存获取到的激活环境
setActiveProfiles(StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(profiles)));
}
}
return this.activeProfiles;
}
}
/**
* Return the property value for the active profiles.
* @since 5.3.4
* @see #ACTIVE_PROFILES_PROPERTY_NAME
*/
@Nullable
protected String doGetActiveProfilesProperty() {
//尝试从属性源中获取激活的环境
return getProperty(ACTIVE_PROFILES_PROPERTY_NAME);
}
@Override
public void setActiveProfiles(String... profiles) {
Assert.notNull(profiles, "Profile array must not be null");
if (logger.isDebugEnabled()) {
logger.debug("Activating profiles " + Arrays.asList(profiles));
}
synchronized (this.activeProfiles) {
//清除之前保留的激活环境集合
this.activeProfiles.clear();
//缓存找到的激活环境
for (String profile : profiles) {
validateProfile(profile);
this.activeProfiles.add(profile);
}
}
}
@Override
public void addActiveProfile(String profile) {
if (logger.isDebugEnabled()) {
logger.debug("Activating profile '" + profile + "'");
}
validateProfile(profile);
//每次添加新的激活环境前,会调用doGetActiveProfiles方法
//这里是顺便将属性源中规定的激活环境也添加进来,顺便清除之前的缓存
doGetActiveProfiles();
synchronized (this.activeProfiles) {
this.activeProfiles.add(profile);
}
}
//和上面获取激活环境套路类似
@Override
public String[] getDefaultProfiles() {
return StringUtils.toStringArray(doGetDefaultProfiles());
}
protected Set<String> doGetDefaultProfiles() {
synchronized (this.defaultProfiles) {
if (this.defaultProfiles.equals(getReservedDefaultProfiles())) {
String profiles = doGetDefaultProfilesProperty();
if (StringUtils.hasText(profiles)) {
setDefaultProfiles(StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(profiles)));
}
}
return this.defaultProfiles;
}
}
@Nullable
protected String doGetDefaultProfilesProperty() {
return getProperty(DEFAULT_PROFILES_PROPERTY_NAME);
}
@Override
public void setDefaultProfiles(String... profiles) {
Assert.notNull(profiles, "Profile array must not be null");
synchronized (this.defaultProfiles) {
this.defaultProfiles.clear();
for (String profile : profiles) {
validateProfile(profile);
this.defaultProfiles.add(profile);
}
}
}
//!profile表示当前环境没被激活才算有效
@Override
@Deprecated
public boolean acceptsProfiles(String... profiles) {
Assert.notEmpty(profiles, "Must specify at least one profile");
for (String profile : profiles) {
if (StringUtils.hasLength(profile) && profile.charAt(0) == '!') {
if (!isProfileActive(profile.substring(1))) {
return true;
}
}
else if (isProfileActive(profile)) {
return true;
}
}
return false;
}
@Override
public boolean acceptsProfiles(Profiles profiles) {
Assert.notNull(profiles, "Profiles must not be null");
return profiles.matches(this::isProfileActive);
}
protected boolean isProfileActive(String profile) {
validateProfile(profile);
Set<String> currentActiveProfiles = doGetActiveProfiles();
return (currentActiveProfiles.contains(profile) ||
(currentActiveProfiles.isEmpty() && doGetDefaultProfiles().contains(profile)));
}
protected void validateProfile(String profile) {
if (!StringUtils.hasText(profile)) {
throw new IllegalArgumentException("Invalid profile [" + profile + "]: must contain text");
}
if (profile.charAt(0) == '!') {
throw new IllegalArgumentException("Invalid profile [" + profile + "]: must not begin with ! operator");
}
}
@Override
public MutablePropertySources getPropertySources() {
return this.propertySources;
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Map<String, Object> getSystemProperties() {
try {
return (Map) System.getProperties();
}
catch (AccessControlException ex) {
return (Map) new ReadOnlySystemAttributesMap() {
@Override
@Nullable
protected String getSystemAttribute(String attributeName) {
try {
return System.getProperty(attributeName);
}
catch (AccessControlException ex) {
if (logger.isInfoEnabled()) {
logger.info("Caught AccessControlException when accessing system property '" +
attributeName + "'; its value will be returned [null]. Reason: " + ex.getMessage());
}
return null;
}
}
};
}
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Map<String, Object> getSystemEnvironment() {
if (suppressGetenvAccess()) {
return Collections.emptyMap();
}
try {
return (Map) System.getenv();
}
catch (AccessControlException ex) {
return (Map) new ReadOnlySystemAttributesMap() {
@Override
@Nullable
protected String getSystemAttribute(String attributeName) {
try {
return System.getenv(attributeName);
}
catch (AccessControlException ex) {
if (logger.isInfoEnabled()) {
logger.info("Caught AccessControlException when accessing system environment variable '" +
attributeName + "'; its value will be returned [null]. Reason: " + ex.getMessage());
}
return null;
}
}
};
}
}
protected boolean suppressGetenvAccess() {
return SpringProperties.getFlag(IGNORE_GETENV_PROPERTY_NAME);
}
@Override
public void merge(ConfigurableEnvironment parent) {
for (PropertySource<?> ps : parent.getPropertySources()) {
if (!this.propertySources.contains(ps.getName())) {
this.propertySources.addLast(ps);
}
}
String[] parentActiveProfiles = parent.getActiveProfiles();
if (!ObjectUtils.isEmpty(parentActiveProfiles)) {
synchronized (this.activeProfiles) {
Collections.addAll(this.activeProfiles, parentActiveProfiles);
}
}
String[] parentDefaultProfiles = parent.getDefaultProfiles();
if (!ObjectUtils.isEmpty(parentDefaultProfiles)) {
synchronized (this.defaultProfiles) {
this.defaultProfiles.remove(RESERVED_DEFAULT_PROFILE_NAME);
Collections.addAll(this.defaultProfiles, parentDefaultProfiles);
}
}
}
//---------------------------------------------------------------------
// Implementation of ConfigurablePropertyResolver interface
//---------------------------------------------------------------------
@Override
public ConfigurableConversionService getConversionService() {
return this.propertyResolver.getConversionService();
}
@Override
public void setConversionService(ConfigurableConversionService conversionService) {
this.propertyResolver.setConversionService(conversionService);
}
@Override
public void setPlaceholderPrefix(String placeholderPrefix) {
this.propertyResolver.setPlaceholderPrefix(placeholderPrefix);
}
@Override
public void setPlaceholderSuffix(String placeholderSuffix) {
this.propertyResolver.setPlaceholderSuffix(placeholderSuffix);
}
@Override
public void setValueSeparator(@Nullable String valueSeparator) {
this.propertyResolver.setValueSeparator(valueSeparator);
}
@Override
public void setIgnoreUnresolvableNestedPlaceholders(boolean ignoreUnresolvableNestedPlaceholders) {
this.propertyResolver.setIgnoreUnresolvableNestedPlaceholders(ignoreUnresolvableNestedPlaceholders);
}
@Override
public void setRequiredProperties(String... requiredProperties) {
this.propertyResolver.setRequiredProperties(requiredProperties);
}
@Override
public void validateRequiredProperties() throws MissingRequiredPropertiesException {
this.propertyResolver.validateRequiredProperties();
}
//---------------------------------------------------------------------
// Implementation of PropertyResolver interface
//---------------------------------------------------------------------
@Override
public boolean containsProperty(String key) {
return this.propertyResolver.containsProperty(key);
}
@Override
@Nullable
public String getProperty(String key) {
return this.propertyResolver.getProperty(key);
}
@Override
public String getProperty(String key, String defaultValue) {
return this.propertyResolver.getProperty(key, defaultValue);
}
@Override
@Nullable
public <T> T getProperty(String key, Class<T> targetType) {
return this.propertyResolver.getProperty(key, targetType);
}
@Override
public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
return this.propertyResolver.getProperty(key, targetType, defaultValue);
}
@Override
public String getRequiredProperty(String key) throws IllegalStateException {
return this.propertyResolver.getRequiredProperty(key);
}
@Override
public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException {
return this.propertyResolver.getRequiredProperty(key, targetType);
}
@Override
public String resolvePlaceholders(String text) {
return this.propertyResolver.resolvePlaceholders(text);
}
@Override
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
return this.propertyResolver.resolveRequiredPlaceholders(text);
}
@Override
public String toString() {
return getClass().getSimpleName() + " {activeProfiles=" + this.activeProfiles +
", defaultProfiles=" + this.defaultProfiles + ", propertySources=" + this.propertySources + "}";
}
}
该抽象类源码比较多,但是很好理解,这里不展开套路了,主要是对profile的处理
public class StandardEnvironment extends AbstractEnvironment {
// 这两个值定义就是在@Value注解要使用它们时的key~~~~~
public static final String SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME = "systemEnvironment";
public static final String SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME = "systemProperties";
public StandardEnvironment() {
}
protected StandardEnvironment(MutablePropertySources propertySources) {
super(propertySources);
}
//往属性源集合中添加两个属性源---》System.getProperties()和System.getenv()
@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
propertySources.addLast(
new PropertiesPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
propertySources.addLast(
new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
}
}
//当前组件包含并且会对外暴露一个当前环境对象的引用
//所有 Spring 应用程序上下文都是 EnvironmentCapable,
//并且该接口主要用于在框架方法中执行 instanceof 检查,
//这些方法接受 BeanFactory 实例,这些实例可能实际上是也可能不是
//ApplicationContext 实例,以便与环境交互(如果确实可用)
//如前所述,ApplicationContext 扩展了 EnvironmentCapable,因此公开了一个 getEnvironment() 方法;
//但是,ConfigurableApplicationContext 重新定义了 getEnvironment() 并缩小了签名以返回 ConfigurableEnvironment。
//效果是 Environment 对象在从 ConfigurableApplicationContext 访问之前是“只读的”,此时它也可以被配置。
public interface EnvironmentCapable {
Environment getEnvironment();
}
在bean的生命周期初始化过程中,会去判断当前bean是否实现了相关aware接口,以便给其注入相关类,这里同理
public interface EnvironmentAware extends Aware {
void setEnvironment(Environment environment);
}
//用于解析字符串值的简单策略接口。由ConfigurableBeanFactory 使用。
// @since 2.5 该接口非常简单,就是个函数式接口~
@FunctionalInterface
public interface StringValueResolver {
@Nullable
String resolveStringValue(String strVal);
}
帮助ConfigurableBeanFactory处理placeholders占位符的。
ConfigurableBeanFactory#resolveEmbeddedValue处理占位符真正干活的间接的就是它~~
// @since 4.3 这个类出现得还是蛮晚的 因为之前都是用内部类的方式实现的~~~~这个实现类是最为强大的 只是SpEL
public class EmbeddedValueResolver implements StringValueResolver {
// BeanExpressionResolver 它支持的是SpEL 可以说非常的强大
// 并且它有BeanExpressionContext就能拿到BeanFactory工厂,就能使用它的`resolveEmbeddedValue`来处理占位符~~~~
// 双重功能都有了~~~拥有了和@Value一样的能力,非常强大~~~
private final BeanExpressionContext exprContext;
@Nullable
private final BeanExpressionResolver exprResolver;
public EmbeddedValueResolver(ConfigurableBeanFactory beanFactory) {
this.exprContext = new BeanExpressionContext(beanFactory, null);
this.exprResolver = beanFactory.getBeanExpressionResolver();
}
@Override
@Nullable
public String resolveStringValue(String strVal) {
// 先使用Bean工厂处理占位符resolveEmbeddedValue
String value = this.exprContext.getBeanFactory().resolveEmbeddedValue(strVal);
// 再使用el表达式参与计算~~~~
if (this.exprResolver != null && value != null) {
Object evaluated = this.exprResolver.evaluate(value, this.exprContext);
value = (evaluated != null ? evaluated.toString() : null);
}
return value;
}
}
关于Bean工厂resolveEmbeddedValue的实现,我们这里也顺带看看:
AbstractBeanFactory :
@Override
@Nullable
public String resolveEmbeddedValue(@Nullable String value) {
if (value == null) {
return null;
}
String result = value;
for (StringValueResolver resolver : this.embeddedValueResolvers) {
result = resolver.resolveStringValue(result);
if (result == null) {
return null;
}
}
return result;
}
public interface EmbeddedValueResolverAware extends Aware {
/**
* Set the StringValueResolver to use for resolving embedded definition values.
*/
void setEmbeddedValueResolver(StringValueResolver resolver);
}
继承该接口的bean,可以在初始化阶段得到一个内嵌的值解析器
我目前正在尝试基于哈希表构建字典。逻辑是:有一个名为 HashTable 的结构,其中包含以下内容: HashFunc HashFunc; PrintFunc PrintEntry; CompareF
如果我有一个指向结构/对象的指针,并且该结构/对象包含另外两个指向其他对象的指针,并且我想删除“包含这两个指针的对象而不破坏它所持有的指针”——我该怎么做这样做吗? 指向对象 A 的指针(包含指向对象
像这样的代码 package main import "fmt" type Hello struct { ID int Raw string } type World []*Hell
我有一个采用以下格式的 CSV: Module, Topic, Sub-topic 它需要能够导入到具有以下格式的 MySQL 数据库中: CREATE TABLE `modules` ( `id
通常我使用类似的东西 copy((uint8_t*)&POD, (uint8_t*)(&POD + 1 ), back_inserter(rawData)); copy((uint8_t*)&PODV
错误 : 联合只能在具有兼容列类型的表上执行。 结构(层:字符串,skyward_number:字符串,skyward_points:字符串)<> 结构(skyward_number:字符串,层:字符
我有一个指向结构的指针数组,我正在尝试使用它们进行 while 循环。我对如何准确初始化它并不完全有信心,但我一直这样做: Entry *newEntry = malloc(sizeof(Entry)
我正在学习 C,我的问题可能很愚蠢,但我很困惑。在这样的函数中: int afunction(somevariables) { if (someconditions)
我现在正在做一项编程作业,我并没有真正完全掌握链接,因为我们还没有涉及它。但是我觉得我需要它来做我想做的事情,因为数组还不够 我创建了一个结构,如下 struct node { float coef;
给定以下代码片段: #include #include #define MAX_SIZE 15 typedef struct{ int touchdowns; int intercepti
struct contact list[3]; int checknullarray() { for(int x=0;x<10;x++) { if(strlen(con
这个问题在这里已经有了答案: 关闭 11 年前。 Possible Duplicate: Empty “for” loop in Facebook ajax what does AJAX call
我刚刚在反射器中浏览了一个文件,并在结构构造函数中看到了这个: this = new Binder.SyntaxNodeOrToken(); 我以前从未见过该术语。有人能解释一下这个赋值在 C# 中的
我经常使用字符串常量,例如: DICT_KEY1 = 'DICT_KEY1' DICT_KEY2 = 'DICT_KEY2' ... 很多时候我不介意实际的文字是什么,只要它们是独一无二的并且对人类读
我是 C 的新手,我不明白为什么下面的代码不起作用: typedef struct{ uint8_t a; uint8_t* b; } test_struct; test_struct
您能否制作一个行为类似于内置类之一的结构,您可以在其中直接分配值而无需调用属性? 前任: RoundedDouble count; count = 5; 而不是使用 RoundedDouble cou
这是我的代码: #include typedef struct { const char *description; float value; int age; } swag
在创建嵌套列表时,我认为 R 具有对列表元素有用的命名结构。我有一个列表列表,并希望应用包含在任何列表中的每个向量的函数。 lapply这样做但随后剥离了列表的命名结构。我该怎么办 lapply嵌套列
我正在做一个用于学习目的的个人组织者,我从来没有使用过 XML,所以我不确定我的解决方案是否是最好的。这是我附带的 XML 文件的基本结构:
我是新来的 nosql概念,所以当我开始学习时 PouchDB ,我找到了这个转换表。我的困惑是,如何PouchDB如果可以说我有多个表,是否意味着我需要创建多个数据库?因为根据我在 pouchdb
我是一名优秀的程序员,十分优秀!