spring @Component註解原理解析
這篇文章主要介紹了spring @Component註解原理解析,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
[email protected] 控制器(注入服務)
[email protected] 業務(注入dao)
[email protected] dao(實現dao訪問)
[email protected] (把普通pojo例項化到spring容器中,相當於配置檔案中的<bean id="" class=""/>)
[email protected],@Service,@Controller,@Repository註解的類,並把這些類納入進spring容器中管理。
@Service public class UserServiceImpl implements UserService { } @Repository public class UserDaoImpl implements UserDao { }
6.<context:annotation-config />
這樣就可以使用@ Resource 、@ PostConstruct、@ PreDestroy、@PersistenceContext、@Autowired、@Required等註解了,就可以實現自動注入
7.<context:component-scan base-package="com.**.impl"/>
Spring給我們提供了context:annotation-config 的簡化的配置方式,自動幫助你完成宣告,並且還自動搜尋@Component,@Repository等標註的類。
context:component-scan除了具有context:annotation-config的功能之外,context:component-scan還可以在指定的package下掃描以及註冊javabean 。還具有自動將帶有@component,@service,@Repository等註解的物件註冊到spring容器中的功能。
因此當使用 context:component-scan 後,就可以將 context:annotation-config移除。
8.spring ioc控制反轉
<--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;
相當於使用@Component("")
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。