詳解spring如何使用注解開發(fā)
在Spring4
之后,要使用注解開發(fā),必須要保證aop
的包導(dǎo)入了。
使用注解需要導(dǎo)入context
約束,增加注解的支持。
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--指定要掃描的包,這個包下的注解會生效--> <context:component-scan base-package="com.chen.project"/> <context:annotation-config/> </beans>
1.bean
@Component
:組件,放 在類上,說明這個類被Spring
管理了,就是bean
。
2.屬性如何注入
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; //等價于<bean id="user" class="com.chen.dao.User"></bean> @Component public class User { public String name; //等價于<property name="name" value="lan"></property> @Value("LAN") public void setName(String name) { this.name = name; } }
3.衍生的注解
@Component
有幾個衍生注解,我們在web
開發(fā)中,會按照mvc
三層架構(gòu)分層!
- dao【
@Repository
】 - service 【
@Service
】 - controller【
@Controller
】
這四個注解功能都是一樣的,都代表將某個類注冊到Spring
中,裝配Bean
。
4.自動裝配置
-@Autowired
通過byType
的方式實現(xiàn)。
@Resource
默認通過byName
的方式實現(xiàn)。
5.作用域
@Scope("singleton") public class User { }
6.小結(jié)
xml
更加萬能,適用于任何場合,維護簡單方便- 注解不是自己的類使用不了,維護相對復(fù)雜!
xml
于注解最佳實踐xml
用來管理bean
- 注解只負責(zé)完成屬性的注入
- 我們在使用的過程中,只需要注意一個問題,必須讓注解生效,就需要開啟注解的支持
<!--指定要掃描的包,這個包下的注解會生效--> <context:component-scan base-package="com.chen.project"/> <context:annotation-config/>
到此這篇關(guān)于詳解spring如何使用注解開發(fā)的文章就介紹到這了,更多相關(guān)spring使用注解開發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
劍指Offer之Java算法習(xí)題精講二叉樹與斐波那契函數(shù)
跟著思路走,之后從簡單題入手,反復(fù)去看,做過之后可能會忘記,之后再做一次,記不住就反復(fù)做,反復(fù)尋求思路和規(guī)律,慢慢積累就會發(fā)現(xiàn)質(zhì)的變化2022-03-03Spring AOP手動實現(xiàn)簡單動態(tài)代理的代碼
今天小編就為大家分享一篇關(guān)于Spring AOP手動實現(xiàn)簡單動態(tài)代理的代碼,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03淺談Spring Cloud zuul http請求轉(zhuǎn)發(fā)原理
這篇文章主要介紹了淺談Spring Cloud zuul http請求轉(zhuǎn)發(fā)原理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08Java多線程實現(xiàn)簡易微信發(fā)紅包的方法實例
這篇文章主要給大家介紹了關(guān)于Java多線程實現(xiàn)簡易微信發(fā)紅包的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01