第一个基于Spring的程序


1、什么是Spring?

Spring是轻量级开源的javaEE框架,其核心是AOP和IOC

1.1、Spring的特点:

1.方便解耦,简化开发

2.AOP编程支持

3.方便程序测试

4.方便和其他框架进行整合

5.方便事务操作

6.降低API开发难度

1.2、Spring下载:

进入网址:[http://repo.spring.io]

详细的Spring下载可参考这篇博客https://blog.csdn.net/frankarmstrong/article/details/69808813

2、Spring 项目中pom.xml文件配置

2.1、导入依赖包:

Spring常用的的依赖包可以通过导入spring-webmvc包自动导入

在xml文件中添加如下配置

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.17</version>
</dependency>

导入依赖包,通过maven即可自动加载。

除此之外,还可以导入其他常用包

这些包在后面的开发中会用到,其相关配置文件如下:

<dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.3.17</version>
      </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.13.2</version>
      </dependency>
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.9.9</version>
      </dependency>

3、利用Spring运行一个简单的程序

打开IDEA编译器,构建如下的目录

image-20220404185532186

首先写一个实体hello类:

public class Hello {
    private  String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

其中./resources/bean.xml为Spring的容器配置文件,那么接下来向Spring容器中注入对象:

<?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="hello" class="com.demo.pro.Hello">
            <property name="str" value="Spring">
            </property>
        </bean>
</beans>

在Spring中每个对象也被叫做bean,每个bean通过Spring容器赋值,比如:<property name="str" value="Spring"></property>

如果对象注入成功,那么在hello类的左侧出现个Spring的标志

看来我们注册成功,那么接下来写一次test类进行测试:

public class mytest {
    public static  void main(String[] args){
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        Hello hello=(Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

其中ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");是拿去Spring容器中对象的前提操作,因此在取得上下文后,再通过context.getBean方法传入id获得的对象,这样我们就拿到了对象。

运行一下:

很高兴,运行成功!!!!


文章作者: fatzard
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 fatzard !
评论
  目录
本站总访问量