1. 程式人生 > >spring—使用註解配置Bean

spring—使用註解配置Bean

Spring2.5開始,出現了註解裝配JavaBean的新方式。註解可以減少程式碼的開發量,spring提供了豐富的註解功能,現在專案中註解的方式使用的也越來越多了。

** 開啟註解掃描

Spring容器預設是禁用註解配置的。開啟註解掃描的方式主要有兩種: <context:component-scan>元件掃描和<context:annotation-config>註解配置。

一般選擇第一種,因為第一種的功能比第二種強大的多。<context:annotation-config>用於啟用那些已經在Spring容器中註冊過的Bean,<context:component-scan>

還可以在指定的package下掃描註冊Bean的功能。

# <context:annotation-config>使用

先加入一個player類和team,需要在Player中的Team屬性加上@autowire註解,因為Player類依賴於team類,當然也可以把@autowire屬性註解放置在任何setter函式上

publicclass Player {

private String name;

privateintage;

@Autowired

private Team team;

public Player() {}

public Player(String name

, intage, Team team) {                                                                                                                                           

super();

this.name = name;

this.age = age;

this.team = team;

}

public String getName() {

returnname;

}

publicvoid setName(String name) {

this.name = name;

}

publicint getAge() {

returnage;

}

publicvoid setAge(intage) {

this.age = age;

}

public Team getTeam() {

returnteam;

}

publicvoid setTeam(Team team) {

this.team = team;

}

@Override

public String toString() {

return"Player [name=" + name + ", age=" + age + ", team=" + team + "]";

}

}

publicclass Team {

private String name;

public Team() {}

public Team(String name) {

this.name = name;

}

public String getName() {

returnname;

}

publicvoid setName(String name) {

this.name = name;

}

@Override

public String toString() {

return"Team [name=" + name + "]";

}

}

spring的配置檔案中配置

<!-- 開啟註解配置 -->

<context:annotation-config></context:annotation-config>

<bean id="player" class="annotation.com.wxh.blog.Player" p:name="wxh" p:age="22"></bean>                                                                      

<bean id="team" class="annotation.com.wxh.blog.Team" p:name="boston"></bean>

結果:Player [name=wxh, age=22, team=Team[name=boston]] ==> success

# 使用更加強大的<context:component-scan>

開啟註解掃描

<!--

對於掃描到的元件,Spring會有預設的命名策略:第一個字母小寫

    在元件上使用註解後需要在Spring的檔案中宣告<context:component-scan/>

    base-package屬性指定一個需要掃描的基類包,Spring會掃描這個包及其子包的所有類

    當需要掃描多個包的時候用“,”分開

 -->

<context:component-scan base-package="annotation.com.wxh.blog"></context:component-scan>                                                             

Player類和Team類中只需要在類的上面加上@Component註解就可以了。因為<context:component-scan>有註冊bean的功能,@Component相當於在springIOC容器中註冊了這個類。

Tips:

>>springIOC容器中存在兩個或者以上Team類的Bean是,自動裝配會失敗,因為預設的@autowiredbyType的,這時候我們需要@qualifer(“value”)指定選擇哪個bean,這時自動裝配就會很據byName裝配。[qualifier:預選的]

>>@component 中有value屬性可以指定BeanId,其實在@service@Controller @repository中都有

** 特殊的註解標註

>> @Component: 通用的構造型註解,標識該類為spring元件[不推薦使用]

>> @Controller: 標識將該類定義為SpringMVC的控制器 ==> Controller

>> @Service: 標識將該類定義為業務服務==> Service

>> @Repository: 標識將該類定義為資料倉庫==> Dao