zoukankan      html  css  js  c++  java
  • Spring框架的IOC之注解方式的快速入门

    1. 步骤一:导入注解开发所有需要的jar包
        * 引入IOC容器必须的6个jar包
        * 多引入一个:Spring框架的AOP的jar包,spring-aop的jar包
    
    2. 步骤二:创建对应的包结构,编写Java的类
        * UserService           -- 接口
        * UserServiceImpl       -- 具体的实现类
    
    3. 步骤三:在src的目录下,创建applicationContext.xml的配置文件,然后引入约束。注意:因为现在想使用注解的方式,那么引入的约束发生了变化
      * spring-framework-3.2.0.RELEASEdocsspring-framework-referencehtmlxsd-config.html,在网页中找到"40.2.8 the context schma"标题
    ,然后将下面标签的内容复制到我们的配置文件中。
        * 需要引入context的约束,具体的约束如下
            <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.xsd
                    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->
    
            </beans>
    
    4. 步骤四:在applicationContext.xml配置文件中开启组件扫描
        * Spring的注解开发:组件扫描
            <context:component-scan base-package="com.huida.demo1"/>
    
        * 注意:可以采用如下配置
            <context:component-scan base-package="com.huida"/> 这样是扫描com.huida包下所有的内容
    
    5. 步骤五:在UserServiceImpl的实现类上添加注解
        * @Component(value="userService")   -- 相当于在XML的配置方式中 <bean id="userService" class="...">
    
    6. 步骤六:编写测试代码
        public class SpringDemo1 {
            @Test
            public void run1(){
                ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
                UserService us = (UserService) ac.getBean("userService");
                us.save();
            }
        }

    使用注解的方式不需要在application.xml中进行复杂的配置。
    使用注解的执行过程:
    在测试代码中创建工厂,加载核心配置文件application.xml的时候,扫描器加载进来,扫描指定包下的所有注解。扫描的时候扫描的组件,s扫描到这个组件后,就会把组件所在类的对象new出来。new出来以后,我们的测试文件就可以拿过来直接使用。



  • 相关阅读:
    2019/9/8
    实现简单的网页登录注册功能 (使用html和css以及javascript技术) 没有美化的日后补全
    测试一些以前的代码
    使用三层开发遵循的原则
    超市管理
    热身训练
    考试第三题
    考试第七题
    考试第10题
    考试第8题
  • 原文地址:https://www.cnblogs.com/wyhluckdog/p/10128226.html
Copyright © 2011-2022 走看看