「SpringBoot」依存性の注入(DI)を利用するサンプル

1.@Serviceで依存性の注入の対象になるクラスを設定する

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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コンテナに依存性の注入を行う

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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();
      }
}

 

Spring Boot

Posted by arkgame