LoginSignup
2
2

More than 5 years have passed since last update.

Spring4を使ってみる。DIしてみる

Posted at

Springおじさんにならなくては

お仕事でSpringを使っていく風潮が出てきたので、設定とかアノテーションとかをさらっておこうと思います。

SpringといえばDIコンテナ!らしいので、ControllerクラスからServiceクラスをDIで呼び出してJSONで表示してみます。

前回まで

bootした

サービスクラス

UserService.java
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserService {

    public User getById(String id){
        User user = new User();
        user.setId(id);
        return user;
    }
}
user.java
// 適当なbean
public class User {
    @Getter
    @Setter
    private String id;
}
  • @Service
    • サービスクラスを宣言するアノテーション
    • @Componentやら@Reponsitoryやら色々あるみたいだけれど、そのクラスの説明的に使い分けるだけで実態はあまり変わらないらしい
  • @Scope
    • @Service、、というかSpringのDIはシングルトンがデフォルトらしい
    • ConfigurableBeanFactoryクラスから定数でscopeを指定できる
    • prototype
      • beanのインジェクションごとに毎回newする
    • request
      • リクエスト毎にインスタンスを使い回す
    • session
      • セッションの範囲でインスタンスを使い回す

サービス使うクラス

@RestController
@RequestMapping("/api/users")
public class UserRestController {

    @Autowired
    UserService userService;

    @RequestMapping(
            value = "/",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<User> getUsers(){
        List<User> users = new ArrayList();
        users.add(userService.getById("minami kotori"));
        users.add(userService.getById("kita kotori"));
        users.add(userService.getById("higashi kotori"));
        users.add(userService.getById("nishi kotori"));
        return users;
    }
}
  • @Autowired
    • @Component(今回は@Service)がアノテートされているクラス群の中から、型一致するものを自動でインジェクションしてくれる
    • interfaceを用意しててDIの候補が複数ある場合は、@Component("hogehoge")で名前を付けて、@Qualifierでその名前を指定してあげるみたい

とりあえず実行

$ gradle bootRun

スクリーンショット 2016-07-16 11.17.47.png

やったー!(・8・)

おまけ

ホットデプロイなるものが出来るらしいので試してみた

依存関係

compile group: 'org.springframework', name: 'springloaded', version: '1.2.6.RELEASE'

でぶろい!

あとはbootRunしたままソースコードをコンパイルしてあげるだけ!簡単かよ!

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2