Spring(二):使用spring框架

一、创建项目(本文使用IDEA,基于Maven,使用Maven非常方便依赖包的管理)

  • 在pom.xml文件中添加spring的依赖,Maven会将相应的包帮我们自动导入项目中

  • <dependency>  
    <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>4.3.9.RELEASE</version>
    </dependency>
  • 项目结构简介:

    • .idea:放在那不用管

    • src:放项目代码的地方

    • pom.xml:Maven的配置文件,用来管理依赖包的

  • 完善项目结构

    • 在src下创建java和resource文件夹

    • 对main/java文件夹,鼠标右键-->Mark Directory as-->Sources Root

    • 对main/resource文件夹,鼠标右键-->Mark Directory as-->Resources Root

    • 在java文件夹下创建com.zhurouwangzi包

    • 在com.zhurouwangzi包下分别创建controller、service、dao、entity包

    • 在resource文件夹下创建spring文件夹,并在spring文件夹下创建applicationContext.xml文件,此文件未spring的配置文件;在resource文件夹下创建jdbc.propertites文件,此文件未jdbc的配置文件

三、添加类,测试

  • 在service包中添加HelloSpring类

  • package com.zhurouwangzi.service;
    public class HelloSpring {
        public HelloSpring(){
            System.out.println("Hello Spring");
        }
    }
  • 在controller包添加HelloSpringTest类用来测试spring

  • package com.zhurouwangzi.controller;
    ​
    import com.zhurouwangzi.service.HelloSpring;
    import org.junit.jupiter.api.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    ​
    public class HelloSpringTest {
        @Test
        public void test1(){
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
            HelloSpring helloSpring = (HelloSpring)applicationContext.getBean("helloSpring");
            System.out.println("end");
        }
    }
  • 在applicationContext.xml文件夹添加一下内容

  • <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean id="helloSpring" class="com.zhurouwangzi.service.HelloSpring"></bean>
    </beans>
  • 启动测试

    • 我们发现HelloSpring类的构造函数被调用了,说明spring帮我们初始化了此类

  • 至此,Spring框架搭建并测试完成

猜你喜欢

转载自www.cnblogs.com/Infancy/p/12587452.html