溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

spring @Component注解原理解析

發(fā)布時(shí)間:2020-09-17 20:02:03 來源:腳本之家 閱讀:277 作者:泡椒炒甜瓜 欄目:編程語言

這篇文章主要介紹了spring @Component注解原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

1.@controller 控制器(注入服務(wù))

2.@service 業(yè)務(wù)(注入dao)

3.@repository dao(實(shí)現(xiàn)dao訪問)

4.@component (把普通pojo實(shí)例化到spring容器中,相當(dāng)于配置文件中的<bean id="" class=""/>)

5.@Component,@Service,@Controller,@Repository注解的類,并把這些類納入進(jìn)spring容器中管理。

@Service
public class UserServiceImpl implements UserService {

} 

@Repository
public class UserDaoImpl implements UserDao {

}

6.<context:annotation-config />

這樣就可以使用@ Resource 、@ PostConstruct、@ PreDestroy、@PersistenceContext、@Autowired、@Required等注解了,就可以實(shí)現(xiàn)自動(dòng)注入

7.<context:component-scan base-package="com.**.impl"/>

Spring給我們提供了context:annotation-config 的簡化的配置方式,自動(dòng)幫助你完成聲明,并且還自動(dòng)搜索@Component , @Controller , @Service , @Repository等標(biāo)注的類。

context:component-scan除了具有context:annotation-config的功能之外,context:component-scan還可以在指定的package下掃描以及注冊javabean 。還具有自動(dòng)將帶有@component,@service,@Repository等注解的對象注冊到spring容器中的功能。

因此當(dāng)使用 context:component-scan 后,就可以將 context:annotation-config移除。

8.spring ioc控制反轉(zhuǎn)

<--spring容器控制對象資源屬性--><bean id="batchNo"
class="com.common.utils.IdGenerator">
<constructor-arg name="datacenterId"
value="${server.datacenterId}"></constructor-arg>  --私有成員變量
<constructor-arg name="workerId"
value="${server.workerId}"></constructor-arg>
</bean>
<--spring依賴注入對象--> 
@Autowired
@Qualifier("batchNo")
private IdGenerator idGenerator;

相當(dāng)于使用@Component("")

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI