天天看點

Spring的注解開發以及整合junit測試

準備工作

  • 導包

    4+2+spring-aop

    Spring的注解開發以及整合junit測試
  • 導入命名空間(限制)
  • 在配置檔案中開啟注解開發

    在base-package中填入需要掃描的包,即該包下所有的類,都可以通過注解來完成開發

Spring的注解開發以及整合junit測試

注解開發

  • 将對象注冊到容器

    早期spring架構開始注解的時候,使用@Component,後來随着開發人員的提議,就一個@Component,不能夠清楚的知道屬于那一層的結構,是以後面引入了

    • @Contorller :用于web層
    • @Service :用于service層
    • @Repository :用于dao層
  • 修改對象的作用範圍

    使用@Scope(scopeName=” “),scopeName的取值可以為singleton和prototype

  • 為對象注入值 @Value(“”)

    1、通過反射的Field指派,但是破壞了對象的封裝性

    Spring的注解開發以及整合junit測試
    2、通過set方法指派(推薦)
    Spring的注解開發以及整合junit測試
  • 引用類型注入

    1、自動裝配注入

    Spring的注解開發以及整合junit測試
    如果有多個不同的car,就會導緻不能注入你想要的引用類型
    Spring的注解開發以及整合junit測試
    Spring的注解開發以及整合junit測試

    為了解決以上的問題,添加與@Autowired搭配使用的@Qualifier(“car2”),這裡就表明,要注入引用類型的car2

    2、手動注入,指定注入哪個名稱的對象

    Spring的注解開發以及整合junit測試
  • 初始化和銷毀
    Spring的注解開發以及整合junit測試

例子:編寫一個User類

package cn.itcast.bean;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.xml.ws.RespectBinding;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

//<bean name="user" class="cn.itcast.bean.User"  />
//@Component("user")
//  @Service("user") // service層
//  @Controller("user") // web層
    @Repository("user")// dao層
//指定對象的作用範圍
@Scope(scopeName="singleton")
public class User {
    private String name;
    @Value("18")
    private Integer age;

    //@Autowired //自動裝配
    //問題:如果比對多個類型一緻的對象.将無法選擇具體注入哪一個對象.
    //@Qualifier("car2")//使用@Qualifier注解告訴spring容器自動裝配哪個名稱的對象

    @Resource(name="car")//手動注入,指定注入哪個名稱的對象
    private Car car;

    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    public String getName() {
        return name;
    }
    @Value("tom")   
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @PostConstruct //在對象被建立後調用.init-method
    public void init(){
        System.out.println("我是初始化方法!");
    }
    @PreDestroy //在銷毀之前調用.destory-method
    public void destory(){
        System.out.println("我是銷毀方法!");
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", car=" + car + "]";
    }

}
           

Spring整合junit測試

在測試類上加上注解配置後,在進行測試的時候,spring會自動加載spring容器,可以節約代碼。

導包 4+2+aop+test

Spring的注解開發以及整合junit測試

配置注解

Spring的注解開發以及整合junit測試

直接測試即可

Spring的注解開發以及整合junit測試