Spring Boot快速入門(三):依賴注入


spring boot使用依賴注入的方式很簡單,只需要給添加相應的注解即可

  • @Service用於標注業務層組件 
  • @Controller用於標注控制層組件
  • @Repository用於標注數據訪問組件,即DAO組件 
  • @Component泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。

然后在使用的地方使用@Autowired即可

創建MyComponent,使用@Component

import org.springframework.stereotype.Component;

@Component//泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。
public class MyComponent
{
    public void hi(String name)
    {
        System.out.println("hi " + name + ",I am MyComponent");
    }
}

 

創建MyController,使用@Controller

import org.springframework.stereotype.Controller;

@Controller//用於標注控制層組件
public class MyController
{
    public void hi(String name)
    {
        System.out.println("hi " + name + ",I am MyController");
    }
}

創建MyRepository,使用@Repository

@Repository//用於標注數據訪問組件,即DAO組件
public class MyRepository
{
    public void hi(String name)
    {
        System.out.println("hi " + name + ",I am MyRepository");
    }
}

創建MyService,MyServiceImpl,使用@Service

public interface MyService
{
    void doSomeThing();
}
import org.springframework.stereotype.Service;

@Service//用於標注業務層組件
public class MyServiceImpl implements MyService
{

    @Override
    public void doSomeThing()
    {
        System.out.println("i am MyServiceImpl");
    }
} 

單元測試

在src/test/java/你的包名/你的項目名ApplicationTests編寫對應的單元測試來驗證是否可以成功注入

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DiApplicationTests
{
    @Autowired//自動注入
    private MyController myController;
    @Autowired//自動注入
    private MyRepository myRepository;
    @Autowired//自動注入
    private MyComponent myComponent;
    @Autowired//自動注入實現了該接口的bean
    private MyService myService;

    @Test
    public void contextLoads()
    {
        myController.hi("lierabbit");
        myRepository.hi("lierabbit");
        myComponent.hi("lierabbit");
        myService.doSomeThing();
    }

}

運行測試用例

hi lierabbit,I am MyController
hi lierabbit,I am MyRepository
hi lierabbit,I am MyComponent
i am MyServiceImpl

顯示以上4句話證明成功注入

源碼地址:https://github.com/LieRabbit/SpringBoot-DI

原文地址:https://lierabbit.cn/2018/01/15/SpringBoot%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A83-%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5/


免責聲明!

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



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