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(); } }