读书人

spring mvc适用注解浅析

发布时间: 2012-06-27 14:20:08 作者: rapoo

spring mvc实用注解浅析

下面是几个spring mvc中比较常用的注解,本人闲暇之余做了些简单总结,参考自《spring 揭秘》,如有错误,请大家见谅,希望大家提出问题,一起解决问题

?

1.注解版的自动绑定(@Autowired)
???? @Autowired是基于注解的依赖注入的核心注解 ,他的存在可以让容器知道需要为当前类注入哪些依赖

 public class NewsProvider{           private INewsHello hello;   private INewsBy by;   @Autowired   public NewsProvider(INewsHello hello,INewsBy by){      this.hello = hello;      this.by = by;   }      }

?or 属性:

 public class NewsProvider{            @Autowired    private INewsHello hello;    @Autowired    private INewsBy by;               }

?ApplicationContext.xml配置加条语句:

  <bean name="code">public class NewsProvider{     @Autowired     @Qualifier("bNewsHello")     private INewsHello hello;     @Autowired     private INewsBy by;}

?到了这里,我们可以看到配置文件里就只有哪些孤独的Bean的定义了!

?

3.? classpath-scanning(@component等)
使用相应的注解对相关的类进行标注后,classpath-scanning功能开始
扫描,当扫描到某个类标注了相应的标注后,就会自动创建给类的
bean,

?配置文件添加一句:

 <beans> <context:component-scan base-package="org.spring21"/></beans>

?<context:component-scan>默认扫描的注解类型是:@Component
@Repository、@Service和@Controller,@Component泛指所有的组件
@Repository指持久层、Dao层,@Service指service层,@Controller指action层、控制层
如:

 @Component  public class NewsProvider{            @Autowired    private INewsHello hello;    @Autowired    private INewsBy by;               }

? 到了这里,xml配置文件完全不用配置bean了。

4.自定义注解:

  <beans>     <context:component-scan base-package="org.spring21"/>        <context: include-filter type="annotation" expression="cn.spring21.annotation.Hello"/>        <context:exclude-filter type="aspectj" expression=".."     </context:component-scan>   </beans>

? 上面我们增加了@Hello作为新的被扫描注解对象,并使用aspectj表达式排除某些扫描结果
??? include-filter和exclude-filter可以使用的type类型有annotation、assignable、regex和aspectj四种

?

读书人网 >VC/MFC

热点推荐