zoukankan      html  css  js  c++  java
  • 关于Spring注解 @Service @Component @Controller @Repository 用法

    @Component 相当于实例化类的对象,其他三个注解可以理解为@Component的子注解或细化。

     在annotaion配置注解中用@Component来表示一个通用注释用于说明一个类是一个spring容器管理的类,此类将有spring扫描并加入容器参与ioc。即就是该类已经拉入到spring的管理中了。

    通过在 classpath 中通过自动扫描方式把组建纳入 spring 容器管理。

    要使用自动扫描机制我们需要打开一下配置信息:

    Bean.xml代码   

    1. <?xml version= "1.0"  encoding= "UTF-8" ?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"   
    3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    4.        xmlns:context="http://www.springframework.org/schema/context"   
    5.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
    6.            http://www.springframework.org/schema/beans/spring-beans-2.5 .xsd  
    7.            http://www.springframework.org/schema/context  
    8.            http://www.springframework.org/schema/context/spring-context-2.5 .xsd">  
    9.            <!--<context:annotation-config />-->
    10.            <context:component-scan base-package="com.zchen" />  
    11.            <!-- 包含annotation-config。spring可以自动去扫描base-pack下面或者子包下面的java文件,如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类注册为bean-->
    12. </beans>  

    注:前面讲要使用注解需要配置: <context:annotation-config />但如果使用了@Component就不需要加它了,因为:<context:component-scan base-package="com.zchen">里面默认了<context:annotation-config />。

    而@Controller, @Service, @Repository是@Component的细化,这三个注解比@Component带有更多的语义,它们分别对应了控制层、服务层、持久层的类。

    @Component泛指组件,当组件不好归类的时候我们可以使用这个注解进行标注,(现在可以都用此注解,可以只使用单一组件)

    Java代码  

    @Repository标签是用来给持久层的类定义一个名字,让Spring根据这个名字关联到这个类。

    例如:

    @Repository(value="userDao")-----也可以直接写@Repository("userDao"),如果没有命名,default name 是class name: UserDaoImpl
    public class UserDaoImpl  implements UserDao{
       ........................................
    }

    保证这个类在bean.xml中<context:component-scan base-pakage="com.czhen">com.czhen pakage dir下。

    注解Repository后可以直接使用@autowire 直接注入 managerImpl中,如:

    @Autowire

    private UserDaoImpl userDaoImpl;

    一般来说@Controller(控制层) 是action入口,调用@Service(业务层) ,Service再调用@Repository (持久层)完成数据持久化。

  • 相关阅读:
    react给input元素中文输入的时候自动转成字符串bug
    charles代理
    es6和es5函数参数和arguments的差别
    Uncaught InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
    Node 开发概述
    对Flutter路由管理库Fluro的封装
    Flutter 切换标签显示对应的列表+Provide状态管理实例
    Flutter 商城实例 分类列表
    Flutter 入口页面及底部导航栏实例制作
    Flutter 建立项目和编写入口文件
  • 原文地址:https://www.cnblogs.com/luoluoshidafu/p/4604451.html
Copyright © 2011-2022 走看看