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实例默认命名:类名首字母小写
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM