@controller 控制器(注入服務)
2、@service 服務(注入dao)
3、@repository dao(實現dao訪問)
4、@component (把普通pojo實例化到spring容器中,相當於配置文件中的<bean id="" class=""/>)
@Component,@Service,@Controller,@Repository注解的類,並把這些類納入進spring容器中管理
下面寫這個是引入component的掃描組件
<context:component-scan base-package=”com.mmnc”>
1、@Service用於標注業務層組件
2、@Controller用於標注控制層組件(如struts中的action)
3、@Repository用於標注數據訪問組件,即DAO組件.
4、@Component泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注
@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");