在refresh()方法中,第一个就是prepareRefresh
准备刷新上下文环境
方法进去之后就是initPropertySources();
此方法
protected void initPropertySources() {
// For subclasses: do nothing by default.
}
spring提供了大量的可扩展的接口提供给我们自己来实现,这里就是其中一个
本来以为只要继承这个类并实现此方法,添加注解@Component就可以了,其实不是的
因为他是调用的自身的方法,所以需要实现其调用类的方法
代码如下
实现类:
public class MyInitApplicationContext extends AnnotationConfigApplicationContext {
public MyInitApplicationContext(Class<?>... componentClasses) {
super(componentClasses);
}
@Override
protected void initPropertySources() {
System.out.println("扩展initPropertySource");
//这里添加了一个name属性到Environment里面,以方便我们在后面用到
getEnvironment().getSystemProperties().put("name", "zxy");
//这里要求Environment中必须包含username属性,如果不包含,则抛出异常
getEnvironment().setRequiredProperties("nmsl");
//在AbstractApplicationContext的initPropertySources()中接下来就是这个方法来验证getEnvironment().validateRequiredProperties();
}
}
测试类:
//注意这里使用的是上面自己实现的类
AnnotationConfigApplicationContext context = new MyInitApplicationContext(Config.class);
报错:
Task :spring-xinjingjie-ioc:MainStart.main() FAILED
扩展initPropertySource
Exception in thread "main" org.springframework.core.env.MissingRequiredPropertiesException: The following properties were declared as required but could not be resolved: [nmsl]
at org.springframework.core.env.AbstractPropertyResolver.validateRequiredProperties(AbstractPropertyResolver.java:145)
at org.springframework.core.env.AbstractEnvironment.validateRequiredProperties(AbstractEnvironment.java:572)
at org.springframework.context.support.AbstractApplicationContext.prepareRefresh(AbstractApplicationContext.java:638)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:93)
at com.xinjingjie.config.MyInitApplicationContext.<init>(MyInitApplicationContext.java:12)
at com.xinjingjie.MainStart.main(MainStart.java:18)
Execution failed for task ':spring-xinjingjie-ioc:MainStart.main()'.
> Process 'command 'C:/Program Files/Java/jdk1.8.0_181/bin/java.exe'' finished with non-zero exit value 1```