Spring(六)使用註解開發

2021-10-05 10:35:14 字數 1452 閱讀 4849

在spring4之後,要使用註解開發,必須要保證aop的包匯入了,pom.xml中新增webmvc依賴即可。

使用註解需要匯入context約束,增加註解的支援!

<?xml version="1.0" encoding="utf-8"?>

xmlns

=""xmlns:xsi

=""xmlns:context

=""xsi:schemalocation=""

>

<

context:annotation-config

/>

beans

>

bean

<

context:component-scan

base-package

="com.kuang.pojo"

/>

屬性如何注入

直接在屬性欄位上加上@value(「***」)

//等價於 

//現在使用註解開發,只需要乙個註解就都解決了

// @component -- 元件

@component

public

class

user

或在set方法上加上@value(「***」):

@component

public

class

user

}

衍生的註解

@component 有幾個衍生註解,我們在web開發中,會按照mvc三層架構分層!

這四個註解功能都是一樣的,都是代表將某個類註冊到spring容器中,裝配bean

自動裝配置

@autowired

@resource

作用域

@component

@scope

("singleton"

)//單例模式,即每次bean容器生產的物件都是同一物件 "prototype"原型模式,即每次bean容器生產的物件為不同物件

public

class

user

}

小結

xml與註解:

xml與註解最佳實踐:

<

context:component-scan

base-package

="com.kuang"

/>

<

context:annotation-config

/>

Spring 使用註解開發

屬性的注入 component 元件,放在類上,說明這個類被spring管理了,就是bean component 元件 等價於 component public class user value 等價於 component public class user衍生註解 這四個註解功能都是一樣的,都是代...

Spring使用註解開發

在對應的實體類上宣告 component註解即可將類註冊為乙個元件,從而被spring掃瞄到。component public class user public user string name public string getname public void setname string na...

Spring使用註解開發

在spring4之後,要使用註解開發,必須要保證aop的包匯入了 使用註解需要匯入context約束,增加註解的支援!xmlns xmlns xsi xmlns context xsi schemalocation context annotation config beans 1.bean com...