Spring注释@Component@Repository@Service@Controller

来源:互联网 发布:天龙八部billing 源码 编辑:程序博客网 时间:2024/05/17 01:23
在用Spring的时候,以前会在配置文件中定义一个类的ID,然后再使用。
<bean id ="userInfoDao" class="com.example.dao.impl.UserInfoDaoImpl">
...
</bean>

然而用下面的Spring提供的注释来定义类的ID,就不用配置文件也可以达到同样的目的。
1,@Component
  @Component是一个一般的注释。用于一般的类。
  @Repository,@Service,@Controller是特殊的预定义的注释。
2,@Repository
 用于数据访问组件,即Dao
    @Repository ("userInfoDao")
     public class UserInfoDaoImpl implements UserInfoDao {...}
3,@Service
   用于业务逻辑组件。
     @Service("myService")
     public class SimpleMyService {...}
     注:@Service有一个参数myService,所以?SimpleMyService的ID是myService
4,@Controller
  用于控制类组件。即Action
    @Controller
     public class MyController{...}
    注:没有参数的情况,类MyController的默认ID是myController.

如果不想用Spring提供的注释的话,可以自己写一个类。这个类首先要实现BeanNameGenerator  接口,再加上下面的定义。
<beans>
   <context:component-scan base-package="org.example"
                           name-generator="org.example.MyNameGenerator" />
</beans>