「SpringBoot」@AutowiredでDI(依存性の注入)をするサンプル

2021年9月27日

1.@Serviceでサービスの作成 DIの対象クラスの定義

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@Service
public class UserService {
public User getinfo(String addr,String username) {
User user = new User();
user.setAddr("test addr");
user.setUsername("yamada");
return user;
}
}
@Service public class UserService { public User getinfo(String addr,String username) { User user = new User(); user.setAddr("test addr"); user.setUsername("yamada"); return user; } }
@Service
public class UserService {
 
   public User getinfo(String addr,String username) {
     User user = new User();
     user.setAddr("test addr");
       user.setUsername("yamada");
       return user;
    }
}

2.@Autowiredで依存性の注入を登録

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@RestController
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/create")
public String create(){
return "test"
}
}
@RestController public class UserController { @Autowired UserService userService; @RequestMapping("/create") public String create(){ return "test" } }
@RestController
public class UserController {

 @Autowired
 UserService userService;
 
 @RequestMapping("/create")
 public String create(){
     return "test"
 }
 
}

 

Spring Boot

Posted by arkgame