@Configuration public class CDPlayerConfig { @Bean(name = "bean1") public CompactDisc sgtPeppers() { return new SgtPeppers(); } @Bean(name = "bean2") public CompactDisc compactDisc() { return new SgtPeppers(); } }
测试
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes= CDPlayerConfig.class,loader=AnnotationConfigContextLoader.class) public class KnightJavaConfigInjectionTest { @Resource(name = "bean2") CompactDisc sgtPeppers; @Test public void test1() { sgtPeppers.play(); } }
我发现两个bean都执行了,而且是是bean1先执行,我的疑问就来了,指定name有啥用?
bean在启动的时候都会注册初始化,不管你用没用@Resource,@Resource只是你哪个地方去使用bean而已
赞,秒懂,非常感谢。