@Autowiredアノテーション

@Autowiredアノテーション

@Autowiredアノテーションとはなんなんでしょう。

DIコンテナはインスタンスを管理するコンテナです。

アクションフォーム(コンポーネント)クラスです。

package jp.co.confrage.test1;

import java.io.Serializable;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import org.hibernate.validator.constraints.NotEmpty;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class SampleForm implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private String age;
}

サービスクラスです。@Serviceアノテーションを使用していますが、基本的に@Componentと同じです。

package jp.co.confrage.test1;

import org.springframework.stereotype.Service;

@Service
public class SampleService {
    public SampleForm get() {
        SampleForm form = new SampleForm();
        form.setAge("20");
        form.setName("yamada");
        
        return form;
    }
}

で、最後にコントローラクラスです。

package jp.co.confrage.test1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class SampleController {
    @Autowired
    private SampleService sampleService;// インスタンス生成していない(newしていない)が使える
    private static final Logger logger = LoggerFactory.getLogger(SampleController.class);
    @RequestMapping(value = "autowired", method = RequestMethod.GET)
    public String get(Model model) {
        logger.info("Welcome Sample Page.");
        model.addAttribute("find", sampleService.get());
        return "test1/autoWired";
    }
}

表示するJSPです。

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Home</title>
</head>
<body>
<h1>
    Hello world!  
</h1>
<P> age is ${find.age}. </P>
<P> name is ${find.name}. </P>
</body>
</html>

上記のようにフィールドの上に@AutoWiredアノテーションをつけると、DIコンテナがその変数の型に代入できるクラスを@Componentの付いているクラスから探し出し、インジェクションしてくれるわけです。

以下のように表示されます。

@Autowiredアノテーション

サービスクラスを使用せずに、アクションフォーム(コンポーネント)クラスに@ComponentアノテーションをつけてあげてDIする、というのが一般的だと思います。

@Autowiredアノテーション

コメント

タイトルとURLをコピーしました