package soundsystem; import org.springframework.stereotype.Component; //@Component注解會告訴Spring創建這個類的實例bean(注意,啟動Component注解功能需要在xml里面配置) @Component("newName") public class SgtPeppers implements CompactDisc { private String title="Pepper's Lonely"; private String artist="The beatles"; SgtPeppers(){ System.out.println("SgtPeppers類實例化"); } public void play() { System.out.println("Sgt Playing:title="+title+" artist="+artist); } }
package soundsystem; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest2 { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void instanceSpring(){ //將配置傳過去,實例化容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); SgtPeppers sp = (SgtPeppers)ctx.getBean("newName"); sp.play(); } }
@Component("newName")//給Bean實例重新命名為:newName
@Component//Bean實例默認命名:類名首字母小寫