参考文献

@Value

1
2
3
4
5
6
7
8
9
10
11
12
13
// org.springframework.beans.factory.annotation.Value
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {

/**
* The actual value expression such as <code>#{systemProperties.myProp}</code>
* or property placeholder such as <code>${my.app.myProp}</code>.
*/
String value();

}

@Value数据来源

1
org.springframework.core.env.PropertySource
1
2
3
4
5
6
7
8
/**
* Return the value associated with the given name,
* or {@code null} if not found.
* @param name the property to find
* @see PropertyResolver#getRequiredProperty(String)
*/
@Nullable
public abstract Object getProperty(String name);
  • 可以将其理解为一个配置源,里面包含了key->value的配置信息,可以通过这个类中提供的方法获取key对应的value信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public interface Environment extends PropertyResolver {

String[] getActiveProfiles();

String[] getDefaultProfiles();

@Deprecated
boolean acceptsProfiles(String... profiles);

boolean acceptsProfiles(Profiles profiles);

// 以下方法为PropertyResolver中的方法,此处展示,粘贴到此处

boolean containsProperty(String key);

@Nullable
String getProperty(String key);

String getProperty(String key, String defaultValue);

@Nullable
<T> T getProperty(String key, Class<T> targetType);

<T> T getProperty(String key, Class<T> targetType, T defaultValue);

String getRequiredProperty(String key) throws IllegalStateException;

<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
*/
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
*/
String resolveRequiredPlaceholders(String text) throws IllegalArgumentException;

}
  • 用来表示环境配置信息,
  • resolvePlaceholders用来解析${text}的,@Value注解最后就是调用这个方法来解析的。

解析@Value的过程

  1. @Value注解的value参数值作为Environment#resolvePlaceholders方法参数进行解析
  2. Environment内部会访问MutablePropertySources来解析
  3. MutablePropertySources内部有多个PropertySource,此时会遍历PropertySource列表,调用PropertySource.getProperty方法来解析key对应的值