spring自动扫描的注解@Component @Controller @Service @Repository

@Component @Controller @Service @Repository的作用

1、@controller 控制器(注入服务)
2、@service 服务(注入dao)
3、@repository dao(实现dao访问)
4、@component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean id=”” class=””/>)


@Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。
下面写这个是引入component的扫描组件

<context:component-scan base-package="包路径"/>

其中base-package为需要扫描的包,可以包括下面的子包,比如:com.iitshare.hapishop、com.iitshare.hapicms


1、@Service用于标注业务层组件
2、@Controller用于标注控制层组件(如struts中的action)
3、@Repository用于标注数据访问组件,即DAO组件.
4、@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。


如下代码:

 1 @RequestMapping("/admin/log")
 2 public class LogController extends
 3     BaseController {
 4      
 5 }
 6 @Service("logServiceImpl")
 7 public class LogServiceImpl extends BaseServiceImpl<Log, Long> implements
 8         LogService {
 9 }
10 @Repository("logDaoImpl")
11 public class LogDaoImpl extends BaseDaoImpl<Log, Long> implements
12     LogDao {
13 }

getBean的默认名称是类名(头字母小写),如果想自定义,可以@Service(“***”)这样来指定。这种bean默认是单例的,如果想改变,可以使用以下方法:
@Service(“beanName”)
@Scope(“prototype”)来改变。
可以使用以下方式指定初始化方法和销毁方法(方法名任意):
@PostConstruct public void init() { }

原文地址:https://www.cnblogs.com/lizhen-home/p/7615601.html