spring中的ApplicationContextInitializer揭秘

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
在它上面有这么几行注释:

Note that clients of any {@link ConfigurableEnvironment} may further customize property sources via the {@link #getPropertySources()} accessor, typically within an {@link org.springframework.context.ApplicationContextInitializer ApplicationContextInitializer}.


意思就是实现ConfigurableEnvironment的应用都有可能通过getPropertySources访问器来自定义property sources,比如通过ApplicationContextInitializer。

那么我们来看看ApplicationContextInitializer这个接口是怎样的


```Java
public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {

/**
* Initialize the given application context.
* @param applicationContext the application to configure
*/
void initialize(C applicationContext);

}

里面就一个initialize函数,但是传入了一个重要的参数applicationContext,而且这个参数继承自ConfigurableApplicationContext,这个接口就如之前提到的实现了EnvironmentCapable接口,有了getEnvironment方法,就可以通过类似如下例子来自定义:

1
2
ConfigurableEnvironment env = applicationContext.getEnvironment();
env.getPropertySources().addLast(new PropertySourceX(...));

那有哪些实现了ApplicationContextInitializer接口的类呢,有什么作用呢?下回再解!

欢迎关注我的公众号:沉迷Spring
显示 Gitment 评论
0%