Spring|@Autowired與new的區別


前兩天寫代碼的時候遇到一個問題,通過new出來的對象,自動注入的屬性總是報空指針的錯誤。到網上查了資料,才發現問題所在,同時也加深了自己對於容器IOC的理解。現在把這個問題記錄一下,僅供大家參考。

【示例】

package com.example.SpringBootStudy.controller;

import com.example.SpringBootStudy.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author jyy
 * @Description {}
 * @Date 2018/12/19 18:28
 */
@RestController
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping(value = "/print",method = RequestMethod.GET)
    public void test() {
        testService.test();
    }
}
package com.example.SpringBootStudy.service;

import com.example.SpringBootStudy.dao.TestDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author jyy
 * @Description {}
 * @Date 2018/12/19 18:26
 */
@Service
public class TestService {

    @Autowired
    private TestDao testDao;

    public void test() {
        testDao.test();
    }
}
package com.example.SpringBootStudy.dao;

import org.springframework.stereotype.Repository;

/**
 * @Author jyy
 * @Description {}
 * @Date 2018/12/19 18:26
 */
@Repository
public class TestDao {

    public void test() {
        System.out.println("調用成功!");
    }
}

輸出結果:

調用成功!

一個很簡單的示例,Controller調用Service,Service調用Dao,輸出結果。

我們將Controller中testService初始化的方式改為new,看下效果:

package com.example.SpringBootStudy.controller;

import com.example.SpringBootStudy.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author jyy
 * @Description {}
 * @Date 2018/12/19 18:28
 */
@RestController
@RequestMapping(value = "/test")
public class TestController {

    //@Autowired
    //private TestService testService;
    private TestService testService = new TestService();

    @RequestMapping(value = "/print", method = RequestMethod.GET)
    public void test() {
        testService.test();
    }
}

輸出結果:

報出空指針異常,跟蹤發現Service中的testDao未正確賦值

總結:@Autowired是從IOC容器中獲取已經初始化的對象,此對象中@Autowired的屬性也已經通過容器完成了注入,整個生命周期都交由容器管控。然而通過new出來的對象,生命周期不受容器管控,自然也無法完成屬性的自動注入。

         

          


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM