zoukankan      html  css  js  c++  java
  • Spring学习笔记(二)IoC(Annotation部分)

    Spring学习笔记(二)IoC(Annotation部分)

    在已经了解使用XML的方式配置IoC,使用annotation的方式会很容易上手。准备用两个部分:annotation方式和xml方式的区别、annotation配置IoC的知识点

    annotation方式和xml方式的区别:

      视频中说道,Spring IoC中,xml的方式不如annotation使用的多。在我见过的项目中,也是这样的。前两天看电信4G的项目中,使用的是SpringMVC,其中IoC使用的就是annotation的方式标注。这样的标注比较灵活。但是不如XML的方式清晰,穿梭于各个文件中,查找相关的注解。在有说明文档的时候很容易明白各个bean,但是不是所有的项目源码都有的。自己比较喜欢XML方式的IoC。可能是因为个人的项目经验比较匮乏。。。

    annotation配置IoC知识点:

      配置beans.xml:

      通xml的方式一样,在<beans>根节点中添加XML的命名空间以及xsd地址和使用annotation的标签,代码中黑色加粗部分:

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-2.5.xsd
        <context:annotation-config />
    </beans>

      @Autowired和@Qualifier:

      @Autowired

      作用:对对应的成员变量自动转配,跟XML方式中的的方式一样,见如XML方式的代码如下:

    <property name="UserDaoImpl">
            <ref bean="xxxx"></ref>
    </property>

      位置:@autowired可以写在属性前面,也可以写在getter和setter前面。但是推荐写在setter前。这样在beans.xml或者后面介绍的@Resource标记的beans中需要的属性进行自动注入

      @Qualifier

      @autowired默认是根据byType的方式在自动注入,当有需同相同类型的bean是,Spring应会找到许多满足条件的bean无法区分从而报错,使用@Qualifier中的value属性来制定用哪一个bean来注入:

        @Autowired
        public void setUserDAO(@Qualifier("u") UserDAO userDAO) {
            this.userDAO = userDAO;
        }

      @Resource (推荐使用这种方式)

      先介绍一个题外的知识点:JSR-250----JCP:java community process是由许多厂家出人在构成的J2EE组织,用于指定java的一些新标准,JSR就是其中一个标准

      @resource同@autowired的功能相似默认是根据ByName找注入的相关bean,如果没有找到再根据ByType,也可以使用name属性指定bean

        @Resource(name="u")
        public void setUserDAO(UserDAO userDAO) {
            this.userDAO = userDAO;
        }    

      @Component@Repository@Service, and @Controller

      相同的注解还有@Component@Repository@Service, and @Controller。在Spring2.5.6中,这几个注解作用相同,用来代替在beans.xml中的bean标签生成的beans

    这样在使用@autowired、@Rrsource是,不需要在xml文件配置beans了

      设置Spring扫描组建的目录:

      <context:annotation-config />
        <context:component-scan base-package="com.xxxx"/>

      @Scope

      对应于XML配置文件的scope属性

    @Component("userService")
    @Scope("singleton")
    public class UserService {
    }

      @PostConstruct与@PreDestroy

      顾名思义,就是标注一个方法,在这个类构造之后执行,住着销毁之前执行

  • 相关阅读:
    invokerequied
    C#如何用正则表达式截取https和带端口的域名
    flex datagrid combox
    java webservice
    Flexlib 控件 http://code.google.com/p/flexlib/
    Git使用
    转:Vim常用命令
    转:oracle连接查询
    Axis2 spring发布WebService
    oracle jdbc example 示例
  • 原文地址:https://www.cnblogs.com/wenlonghor/p/3294867.html
Copyright © 2011-2022 走看看