1. 程式人生 > >spring學習筆記(12)——使用註解方式配置bean

spring學習筆記(12)——使用註解方式配置bean

常用的註解

常用的有四個註解

  • Controller: 用於控制器的註解
  • Service : 用於service的註解
  • Component: 用於基本元件的註解
  • Repository:用於Dao層的註解
  • 其實,對於spring來說,它根本無法識別controller,service等,它只知道只要你加了以上四個註解,它就幫你建立bean
  • 簡單來說,就是如果你在控制器上使用Component註解,或者使用Repository註解也是可以的,四種註解可以混用
  • 但是,我們一般都按照上方所示的規則來使用註解,這樣程式碼才有可讀性

使用註解

一般程式中都是三層架構,我們來簡單模擬一下

寫一個控制器,加上Controller註解

package com.zj.annotation.controller;

import org.springframework.stereotype.Controller;

@Controller
public class TestController {
    @Override
    public String toString() {
        return "testController";
    }
}

寫一個service介面

package com.zj.annotation.service;

public
interface TestService { void add(); }

實現類

package com.zj.annotation.service;

import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

@Service 
public class TestServiceImpl implements TestService {

    @Override
    public void add() {
        System.out.println("service impl add....."
); } }

DAO層使用Repository註解,其它的使用Component,使用方法一樣,這裡就不寫出來了

加上註解之後,spring並不會幫我們建立bean,還需要一個步驟:在配置檔案中配置掃描的包

<!-- 掃描com.zj.annotation包以及所有子包,為所有加了註解的類建立bean -->
<context:component-scan base-package="com.zj.annotation">
</context:component-scan>

寫一個測試方法

public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");

        TestController testController = (TestController) ctx.getBean("testController");
        System.out.println(testController);

        TestService testService = (TestService) ctx.getBean("testServiceImpl");
        testService.add();
    }

執行結果
這裡寫圖片描述

使用註解建立bean成功

預設命名規則

  • 我們使用註解配置bean的時候,並沒有指定bean的id,那麼spring幫我們建立bean的時候會給一個預設的id,id為類名首字母小寫。如TestController-> testController
  • 我們也可以指定bean的名稱(id),使用註解的value屬性,如@Service(value=”myService”)
  • value屬性是註解的預設屬性,可以省略,即@Service(“myService”)

掃描的配置

resource-pattern

使用resource-pattern屬性,配置掃描的條件

<context:component-scan base-package="com.zj.annotation"
    resource-pattern="service/*.class">
</context:component-scan>

只掃描service註解

使用context:include-filter

該子節點表示要包含的目標類

type : annotation表示只包含某個註解

<context:component-scan base-package="com.zj.annotation" use-default-filters="true">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

只掃描有Controller註解的

type:assignable表示只包含某個類

<context:component-scan base-package="com.zj.annotation" use-default-filters="true">
    <context:include-filter type="assignable" expression="com.zj.annotation.controller.TestController"/>
</context:component-scan>

只掃描TestController這個類

注意

  • context:include-filter需要配合use-default-filters=”true”才有效

使用context:exclude-filter

該子節點表示要排除的目標類

  • context:exclude-filter和context:include-filter恰好相反,但是使用方法是一樣的,也有type屬性也有assignable和annotation