spring自動掃描的註解@Component @Controller @Service @Repository
阿新 • • 發佈:2017-09-30
改變 包括 alt init 實例 gda context nts str
@Component @Controller @Service @Repository的作用
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.iitshare"
/>
其中base-package為需要掃描的包,可以包括下面的子包,比如:com.iitshare.hapishop、com.iitshare.hapicms
1、@Service用於標註業務層組件
2、@Controller用於標註控制層組件(如struts中的action)
3、@Repository用於標註數據訪問組件,即DAO組件.
4、@Component泛指組件,當組件不好歸類的時候,我們可以使用這個註解進行標註。
如下代碼:
@RequestMapping
(
"/admin/log"
)
public
class
LogController
extends
BaseController {
}
@Service
(
"logServiceImpl"
)
public
class
LogServiceImpl
extends
BaseServiceImpl<Log, Long>
implements
LogService {
}
@Repository
(
"logDaoImpl"
)
public
class
LogDaoImpl
extends
BaseDaoImpl<Log, Long>
implements
LogDao {
}
getBean的默認名稱是類名(頭字母小寫),如果想自定義,可以@Service(“***”)這樣來指定。這種bean默認是單例的,如果想改變,可以使用以下方法:
@Service(“beanName”)
@Scope(“prototype”)來改變。
可以使用以下方式指定初始化方法和銷毀方法(方法名任意):
@PostConstruct public void init() { }
spring自動掃描的註解@Component @Controller @Service @Repository