- 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--------------
[點擊並拖拽以移動]
- mysql分庫分表策略
- 分佈式事務
- Mysql join兩張表後做groupby,如何將表二爲空的數據,結果出來count的值爲0
- Join情況下,爲什麼要用到where1=1;
- http 網絡編程