問題記錄

  1. spring 有幾種注入方式

構造函數注入

setter注入

註解注入

以下是構造函數注入方式:

import org.springframework.stereotype.Component;

@Component
public class User {
public void userName(){
System.out.println("1--------------");

}

}

[點擊並拖拽以移動]

UserServiceImp類依賴於User類,將User類以構造函數注入的方式注入

import org.springframework.stereotype.Repository;

@Repository(value = "userServiceImp")
public class UserServiceImp {
private User user;

public UserServiceImp(User user){
    this.user = user;
}

public void getName(){
    user.userName();
}

}

[點擊並拖拽以移動]

單元測試,驗證是否真的有注入

import com.example.springbootexample.Controller.UserServiceImp;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)br/>@SpringBootTest
public class SpringbootExampleApplicationTests {
@Resource(name = "userServiceImp")
UserServiceImp serviceImp;

@Test
public void getNameTest() {
    serviceImp.getName();

}

}

[點擊並拖拽以移動]

單元測試執行結果:

SpringbootExampleApplicationTests in 7.047 seconds (JVM running for 12.118)
1--------------

[點擊並拖拽以移動]

  1. mysql分庫分表策略
  2. 分佈式事務
  3. Mysql join兩張表後做groupby,如何將表二爲空的數據,結果出來count的值爲0
  4. Join情況下,爲什麼要用到where1=1;
  5. http 網絡編程
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章