扩展initPropertySources()方法

在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```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值