Spring Bean 注解

Spring 提供了几个注解,表示 向Spring容器注册Bean。

@Controller:对应控制器的Bean

import org.springframework.stereotype.Controller;

@Controller
public class PersonController {

}

 

@Service:对应的是业务层Bean

import org.springframework.stereotype.Service;

@Service
public class PersonServiceImpl implements PersonService {

}

 

@Repository:对应数据访问层Bean

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonRepository extends JpaRepository<Person, Long>, JpaSpecificationExecutor<Person> {

}

 

@Component:是所有受Spring 管理组件的通用形式,@Component注解可以放在类的头上,@Component不推荐使用。

 

这几个注解,在功能上是相同的,都是辅助@ComponentScan 实现组件扫描,把注解的bean注册到Spring 容器中,受Spring管理。只是在表意上,在控制器类用@Controller,Service成用@Service,数据访问层用@Repository,这样比都用@Component更清楚一些。

 

posted on 2021-01-15 14:50  dreamstar  阅读(150)  评论(0编辑  收藏  举报