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

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

  • @Service用於標註業務層組件 
  • @Controller用於標註控制層組件
  • @Repository用於標註數據訪問組件,即DAO組件 
  • @Component泛指組件,當組件很差歸類的時候,咱們能夠使用這個註解進行標註。

而後在使用的地方使用@Autowired便可git

建立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編寫對應的單元測試來驗證是否能夠成功注入github

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();
    }

}

運行測試用例spring

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

顯示以上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/
blog

相關文章
相關標籤/搜索