Spring In Action-2.1-02-@Component注解给Bean命名
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实例默认命名:类名首字母小写