Spring注解驱动开发:容器(深入源码)

AnnotationConfigApplicationContext(注释配置应用程序上下文)

在这里插入图片描述
在这里插入图片描述
在AnnotationConfigApplicationContext中,定义了两个属性分别是在这里插入图片描述
reader用于编程带注释的bean类,scanner用于扫描bean候选对象。
AnnotationConfigApplicationContext的构造方法大体上可以分为两种:
第一种:

/**
* Create a new AnnotationConfigApplicationContext, scanning for bean definitions
* in the given packages and automatically refreshing the context.
* @param basePackages the packages to check for annotated classes
*/
public AnnotationConfigApplicationContext(String… basePackages) {
this();
scan(basePackages);
refresh();
}
这个方式的最大特征就是自定义扫描包,通过scan这个方法扫描,然后refresh刷新容器。

第二种:

/**
* Create a new AnnotationConfigApplicationContext, deriving bean definitions
* from the given annotated classes and automatically refreshing the context.
* @param annotatedClasses one or more annotated classes,
* e.g. {@link Configuration @Configuration} classes
*/
public AnnotationConfigApplicationContext(Class<?>… annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}

这个方式的最大特征就是可以将配置信息(标注了@Configuration的类)放到参数方法中。
第三种:

/**
* Create a new AnnotationConfigApplicationContext that needs to be populated
* through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
/
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
/
*
* Create a new AnnotationConfigApplicationContext with the given DefaultListableBeanFactory.
* @param beanFactory the DefaultListableBeanFactory instance to use for this context
*/
public AnnotationConfigApplicationContext(DefaultListableBeanFactory beanFactory) {
super(beanFactory);
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}

这种构造的最大特征是都初始化了reader 和 scanner,第二种区别于的地方在于他将所获得的beanFactory(管理默认所有的已经实例化的bean的工程)。
其背后的super()过于复杂就不深入专研。

使用
@Test
	public void test01() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		//没有指定配置的类
		context.getEnvironment().setActiveProfiles("test","dev");
		
		context.register(MainConfigOfProfile.class);
		
		context.refresh();
		
		String[] definitionNames = context.getBeanDefinitionNames();
		for(String string : definitionNames) {
			System.out.println(string);
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值