Spring注解之@Component詳細解析


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

 

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

源代碼:

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

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

  

案例:

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

@Component

public class University {

          to do sthing...

}

獲取bean方式:

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

 

 


 

b.指定bean的名稱

@Component("university1")

public class University {

          to do sthing...

}

 

獲取bean方式:

 

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

  

  

  

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM