LoginSignup
268

More than 5 years have passed since last update.

@Component、@Service、@Repository、@Controllerの違いについて

Posted at

Springアノテーション「@Component@Service@Repository@Controller」について、動きとして基本的同じであり、何れもアノテーションが付与されたクラスをSpringのDIコンテナにbeanとして登録します。使い分けとしては、Spring MVCにおいてコントローラー層のクラスには@Contoroller、サービス層のクラスには@Serivice、データ層のクラスには@Repository、どれにも当てはまらない場合は@Componentを付けます。

@Controller

Spring MVCでコントローラー層のクラスに付与する。
Controller は、主に以下の役割を担う。
・画面遷移の制御
・ドメイン層の Service の呼出 (主処理を実行する)

@Controller
@RequestMapping("findProduct")
public class FindProductController {

    @Inject
    FindProductService findProductService;

    @RequestMapping(value="list")
    public String list(Model model) {
        Collection<Product> products = findProductService.findAll();
        model.addAttribute("products", products);
        return "product/list";
    }
}

@Service

Sping MVCでサービス層のクラス(ビジネスロジック等)に付与する。
Service は業務処理を提供する。

@Service
public class FindProductServiceImp implements FindProductService {

    @Inject
    FindProductRepository findProductRepository;

    public Todo findAll() {

        Collection<Product> products = findProductRepository.findAll();

        if (products == null) {

            // エラー処理
            ...
        }
        return products;
    }
}

@Repository

Spring MVCでデータ層のクラス(DAO等のDBアクセスを行うクラス)に付与する。

@Repository
public class FindProductRepositoryImpl implements FindProductRepository {

    private Collection<Product> products;

    @Override
    public Collection<Product> findAll() {
        return products;
    }
}

@Component

Spring MVCに限らず、SpringのDIコンテナにbeanとして登録したいクラスへ付与する。

@Component
public class checkComponentImp implements checkComponent{

    @Override
    public boolean check(BLogicParam param) {
        ...
    }
}

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
268