栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Parsing the process of Bean Creation by AnnotationConfigWebApplicationContext

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Parsing the process of Bean Creation by AnnotationConfigWebApplicationContext

        You know Bean is a Definition in Spring framework, It is  everywhere in our work and our projects, how does it work?  I will  write a blog to deepen impression by studying the source code of Spring framework.

AnnotationConfigWebApplicationContext 1.  Register Configuration Class

        Let me show you a couple of examples below.

        First of all, we can define a  configuration class, it means  that Spring will scan the similar classes for future use.

        Anyway we must register our class with the Spring container.

public class AnnotationConfigWebApplicationContextTests{

@Configuration("myConfig")
	static class Config {

		@Bean
		public TestBean myTestBean() {
			return new TestBean();
		}
	}


	static class TestBean {
	}
}

        I believe you know AnnotationConfigApplicationContext, similarly, it can help us to scan all satisfied bean , you only provide a param  as a base-package. 

       There are two methods to register my definition bean ,it means that we can put our definition bean into BeanFactory.

        Let's look at a method on AnnotationConfigWebApplicationContext as follows.

	public void register(Class... annotatedClasses) {
		Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
		this.annotatedClasses.addAll(Arrays.asList(annotatedClasses));
	}

         So we can use the register method to get our definition bean.

@Test
public void registerSingleClass{

 AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext();
 ctx.register(Config.class);
  //  refresh BeanFactory, init or recreated.
 ctx.refresh();
 TestBean testBean=ctx.getBean(TestBean.class);
 assertNotNull(testBean);

}

        Tip:  we must execute  the ctx.refresh() before geting bean, otherwise, it will generate a exception of BeanFactory ! 

        We can easily get correct result !          Another way , we can use the setConfigLOcation()  method to register our definition bean.

	@Test
	@SuppressWarnings("resource")
	public void configLocationWithSingleClass() {
		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.setConfigLocation(Config.class.getName());
		ctx.refresh();

		TestBean bean = ctx.getBean(TestBean.class);
		assertNotNull(bean);
	}

        It is not hard to see how the method can be implemented as well.  

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/322262.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号