Spring註解開發

2021-10-11 02:46:29 字數 2289 閱讀 8896

配置類注入

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

xmlns

=""xmlns:xsi

=""xmlns:context

=""xsi:schemalocation=""

>

<

context:component-scan

base-package

="xpu"

/>

beans

>

建立乙個user類

//@component:元件,放在這個類上,就說明這個類被spring管理了,就是bean!

@value可以給屬性注入值,可以直接在屬性上注入,不需要set方法,如果有set方法,也可以在set方法上注入。

@component

@scope

("singleton"

)//單例模式,prototype原型模式

public

class

user

}

*[html]:

衍生的註解:

dao層: [@repository]

service層:[@service]

controller層:[@controller]

這四個註解功能都是一樣的,都是代表某個類放入spring當中,裝配bean。

@controller

public

class

usercontroller

@repository

public

class

userdao

@service

public

class

userservice

public

class

mytest

}

不需要xml檔案

首先建立乙個配置類

*[html]:

註冊乙個bean,就相當於我們之前寫的乙個bean標籤

這個方法的名字,就相當於bean標籤中的id屬性,id="getuser"

這個方法的返回值,就相當於bean標籤中的class屬性,class="new user()"*****=class="xpu.pojo.user"

@configuration

@import

(xpu.config.myconfig2.

class

)//和bean一樣,可以多個配置類

public

class

myconfig

/* @bean

public cat getcat()/

}

配置類和xml檔案一樣,可以定義多個

@configuration

public

class

myconfig2

}

掃瞄乙個配置類,將另外的配置類import到乙個配置類中

user類需要component將類放入bean

@component

public

class

user

public

void

setcat

(cat cat)

@override

public string tostring()

';}public string getname()

@value

("張三"

)public

void

setname

(string name)

}

@component

public

class

catpublic string getname()

@value

("咪咪"

)public

void

setname

(string name)

}

public

class

configtest

}

Spring註解開發

spring註解開發 dao層用的註解 repository service層的註解 service controller表現層的註解 controller 以上的三個註解都是用 componment新增三個衍生的註解 屬性依賴注入 value的屬性注入 value wwtmy love 注入的是屬...

spring註解開發

第一步,設定xml約束檔案 第一步,設定xml約束檔案 xmlns xsi xmlns context xsi schemalocation spring beans.xsd spring context.xsd 第二步,定義bean 除了 component外,spring提供了3個功能基本和 c...

Spring註解開發

在spring4之後,要使用註解開發,但是必須保證aop的包存在 使用註解必須保證匯入context約束增加註解的支援 xmlns xmlns xsi xmlns context xsi schemalocation spring beans.xsd spring context.xsd conte...