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