「SpringBoot」依存性の注入(DI)を利用するサンプル
1.@Serviceで依存性の注入の対象になるクラスを設定する
package com.arkgame.study;
import org.springframework.stereotype.Service;
@Service
public class Test {
public String getAddr() {
return "tokyo";
}
}
package com.arkgame.study;
import org.springframework.stereotype.Service;
@Service
public class Test {
public String getAddr() {
return "tokyo";
}
}
package com.arkgame.study; import org.springframework.stereotype.Service; @Service public class Test { public String getAddr() { return "tokyo"; } }
アノテーションの説明
@Service
サービスクラスにつけます
@Component
DIコンテナに登録する場合につけます
@Controller
コントローラークラスにつけます
@Repository
DAOのクラスにつけます
2.@AutowiredでDIコンテナに依存性の注入を行う
package com.arkgame.study;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MainController {
@Autowired
Test test;
@GetMapping("/addr")
public String funcA() {
return test.getAddr();
}
}
package com.arkgame.study;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MainController {
@Autowired
Test test;
@GetMapping("/addr")
public String funcA() {
return test.getAddr();
}
}
package com.arkgame.study; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MainController { @Autowired Test test; @GetMapping("/addr") public String funcA() { return test.getAddr(); } }