Spring註解之@Component詳細解析

摘自: https://blog.csdn.net/lycyl/article/details/82865009java

 

@Component是一個元註解,意思是能夠註解其餘類註解,如@Controller @Service @Repository @Aspect。官方的原話是:帶此註解的類看爲組件,當使用基於註解的配置和類路徑掃描的時候,這些類就會被實例化。其餘類級別的註解也能夠被認定爲是一種特殊類型的組件,好比@Repository @Aspect。因此,@Component能夠註解其餘類註解。

spring

源代碼:app

           @Target({java.lang.annotation.ElementType.TYPE})
           @Retention(RetentionPolicy.RUNTIME)
           @Documented
           public @interface Component {

        //這個值可能做爲邏輯組件(即類)的名稱,在自動掃描的時候轉化爲spring bean,即至關<bean id="" class="" />中的id
                   public abstract String value();
            }

  

案例:.net

a.不指定bean的名稱,默認爲類名首字母小寫universityxml

@Component

public class University {

          to do sthing...

}

獲取bean方式:blog

ApplicationContext ctx  = new ClassPathXmlApplicationContext("./config/applicationContext.xml");
           University ust = (University) ctx.getBean("university");

 

 


 

b.指定bean的名稱get

@Component("university1")

public class University {

          to do sthing...

}

 

獲取bean方式:it

 

ApplicationContext ctx  = new ClassPathXmlApplicationContext("./config/applicationContext.xml");
           University ust = (University) ctx.getBean("university1");
相關文章
相關標籤/搜索