EWEADN

  1. 创建一个Maven的项目,我的项目结构如下:
    我的目录
  2. 在pom文件里写下需要导入的依赖:
    ```







    ```
  3. 在Java文件夹下新建package,在package包下新建接口及其实现类
    接口:
    ```
    public interface SomeService {
    void doSome();
    }

    **实现类:**

    public class SomeServiceImpl implements SomeService {

     public SomeServiceImpl() {
         System.out.println("创建SomeServiceImpl对象");
     }
    
     @Override
     public void doSome() {
         System.out.println("执行SomeServiceImpl里的doSome()方法");
     }

    }

    ```
  4. 在resources目录下新建applicationContext.xml文件
  • 我们需要在spring容器的配置文件中进行注册该Bean
  • spring使用的配置文件为xml文件,当然需要引入约束文件,一般将spring的配置文件命名为applicationContext.xml
    ```

     <!--注册Servcie
     其造价于如下代码:   SomeServiceImpl someService = new SomeServiceImpl();
     其底层是通过反射机制创建的someService对象
        Object someService = Class.forName("com.abc.service.SomeServiceImpl").newInstance();
     -->
     <bean id="someService" class="com.abc.service.SomeServiceImpl"/>

    ```
  • spring的根元素是benas显然是注册Bean,子标签是Bean
  • 注册:<bean id="someService" class="com.abc.service.SomeServiceImpl"/>
  • id属性为了唯一确定一个对象,class属性里边应写类全名
  1. 注册完毕后我们要在测试类中获取spring容器,而获取Spring容器有两种方式。
    ```
    package com.abc.service;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.context.support.FileSystemXmlApplicationContext;

    public class SomeServiceImplTTest {
    // spring容器获取的两种方式
    @Test
    public void test01(){
    //在类路径下加载Spring配置文件
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    //在当前目录的根下加载该配置文件,路径应为文件实际存放的目录
    ApplicationContext ac2 = new FileSystemXmlApplicationContext("D:\IDEA-workspace\01-first(Spring)\src\main\resources\applicationContext.xml");
    System.out.println(ac2);
    }

     @Test
     public void test02() {
          // 加载Spring配置文件,创建Spring容器对象
          ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
          //调用spring容器的getBean方法获取carImpl,方法参数为bean的id
          SomeService service = (SomeService) ac.getBean("SomeService");
          service.doSome();
         }
     }
    ```
  2. Spring入门程序到此就结束了

分类:

技术点:

相关文章:

  • 2020-03-29
  • 2022-01-02
  • 2021-10-09
  • 2021-05-01
  • 2021-11-02
  • 2019-06-26
  • 2021-11-04
猜你喜欢
  • 2021-07-27
  • 2019-03-07
  • 2021-11-03
  • 2022-01-21
  • 2021-05-29
  • 2022-01-14
  • 2021-06-24
相关资源
相似解决方案