Spring注解基本解读

在一个类中使用Spring对象,办法如下:

  • 使用注解的形式注入
  • 从ApplicationContext中获取。

T t = new ApplicationContext.getBean("xxxid");

核心知识

基础讲解

Spring的注解只有在Spring的XML配置文件的配置路径包含中才会有效。

  • SpringMVC的Controller层的配置扫描。
  • Spring管理的其他配置扫描

不建议某一个类,既让Spring扫描到,又让SpringMVC扫描到,这样会出问题,比如说在使用事务的时候,就有可能出现问题。
ps: new出来的对象,不是交给Spring进行管理的,所以如果new的哪个类里面又使用到注解的,会抛出空指针异常。

常用注解

  • @Component 万金油,当不好归类的时候,可以使用此注解。
  • @Controller 控制层注解。
  • @Sevevice 业务逻辑层注解。
  • @Repository 数据访问层注解。

扫描区分

比如说SpringMVC的配置xml文件中就有存在这样的描述。

 <!-- 只扫描base-package下的用Controller注解的类。 --> 
<context:component-scan base-package="com.mc.bsframe.controller">   <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />   <!-- 必须要包括ControllerAdvice才能处理全局异常。 -->
  <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> </context:component-scan>`

 

比如说Spring的配置XML中也存在这样的描述:

    <!-- 会自动扫描com.mc.bsframe下的所有包,包括子包下除了@Controller的类。 -->
    <scpan:component-scan base-package="com.mc.bsframe">
        <scpan:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        <scpan:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    </scpan:component-scan>

 

posted @ 2016-08-18 21:39  LiuChunfu  阅读(660)  评论(0编辑  收藏  举报