spring @component的作用

hello_xusir發表於2016-12-01
1、@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”>    

其中base-package為需要掃描的包(含所有子包) 
       1、@Service用於標註業務層元件 
       2、@Controller用於標註控制層元件(如struts中的action) 
       3、@Repository用於標註資料訪問元件,即DAO元件. 
       4、@Component泛指元件,當元件不好歸類的時候,我們可以使用這個註解進行標註。    
           @Service public class UserServiceImpl implements UserService { } 
           @Repository public class UserDaoImpl implements UserDao { } getBean的預設名稱是類名(頭字母小寫),如果想自定義,可以@Service(“***”)               這樣來指定,這種bean預設是單例的,如果想改變,可以使用@Service(“beanName”) 
           @Scope(“prototype”)來改變。可以使用以下方式指定初始化方法和銷燬方法(方法名任意): @PostConstruct public void init() { } 

相關文章