spring注解开发AnnotationConfigApplicationContext的使用
https://www.cnblogs.com/kaituorensheng/p/8024199.html
注:
@Configuration可理解为用spring的时候xml里面的<beans>标签
@Bean可理解为用spring的时候xml里面的<bean>标签
下面是两种上下文的生成方式,第一种需要执行register,refresh,第二种不需要。原因可以看第三段的源码,第二种是源码里面调用了register与refresh。
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class); ctx.refresh(); ////////////////////////////////////// AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); ////////////////////////////////source code public AnnotationConfigApplicationContext() { this.reader = new AnnotatedBeanDefinitionReader(this); this.scanner = new ClassPathBeanDefinitionScanner(this); } public AnnotationConfigApplicationContext(Class... annotatedClasses) { this(); this.register(annotatedClasses); this.refresh(); }
一种方法用于获取一个类没有多个bean的场景,直接通过类名获取bean
public class JavaConfigTest { public static void main(String[] arg) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); Entitlement ent = ctx.getBean(Entitlement.class); System.out.println(ent.getName()); System.out.println(ent.getTime()); } }
一种方法用于获取一个类有多个bean的场景,通过名称获取bean
package com.pandx.test.config; import com.pandx.test.Entitlement; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean(name="entitlement") public Entitlement entitlement() { Entitlement ent = new Entitlement(); ent.setName("Entitlement"); ent.setTime(1); return ent; } @Bean(name="entitlement2") public Entitlement entitlement2() { Entitlement ent = new Entitlement(); ent.setName("Entitlement2"); ent.setTime(2); return ent; } }
public class JavaConfigTest { public static void main(String[] arg) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); Entitlement ent = (Entitlement)ctx.getBean("entitlement"); System.out.println(ent.getName()); System.out.println(ent.getTime()); Entitlement ent2 = (Entitlement)ctx.getBean("entitlement2"); System.out.println(ent2.getName()); System.out.println(ent2.getTime()); ctx.close(); } }