Spring系列-(1)Spring入门

Spring简介

Spring 是一个开源框架,是为了解决企业应用程序开发复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许您选择使用哪一个组件,同时为 J2EE 应用程序开发提供集成的框架。这也是Spring的目的,Spring的大体内容可分为两部分IOC和AOP

IOC

IOC—Inversion Of Control,即“控制反转”,它表示将你需要创建的对象交给容器控制,让容器帮你创建对象,在传统的对象创建中,我们都是通过直接new的方式去创建对象,由程序主动去创建依赖对象,但是IOC是有一个特定的容器来创建你所需的对象,这叫控制。 传统应用程序是我们自己在对象中主动控制去直接获取依赖对象,也就是正转,而IOC容器帮我们查找及注入依赖对象,对象只是被动的接受依赖对象,这叫反转。

传统创对象的方式 IOC创建对象方式

AOP

简单的HelloWorld

1.导包 idea创建一个普通的maven项目,在pom.xml导入spring-webmvc的包,导此包的好处是把IOC基本的核心包都导进来了,不需要一个一个包去导入

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

2.创建Hello.java 在src下的main下的java下创建Hello类

public class Hello {
          
   
    private String name;
    private String context;

    public Hello() {
          
   
    }

    public Hello(String name, String context) {
          
   
        this.name = name;
        this.context = context;
    }

    public String getName() {
          
   
        return name;
    }

    public void setName(String name) {
          
   
        this.name = name;
    }

    public String getContext() {
          
   
        return context;
    }

    public void setContext(String context) {
          
   
        this.context = context;
    }

    @Override
    public String toString() {
          
   
        return "Hello{" +
                "name=" + name +  +
                ", context=" + context +  +
                };
    }
}

3.创建bean.xml 在src下的main下的resources下创建一个叫bean的xml文件,在bean.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
        https://www.springframework.org/schema/beans/spring-beans.xsd>
    <bean id="hello" class="Hello">
        <property name="name" value="adai"></property>
        <property name="context" value="hello"></property>
    </bean>
</beans>

4.创建Mytest测试类 在src下的test下的java创建Mytest类,类名可以自定义

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest {
          
   
    public static void main(String[] args) {
          
   
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Hello hello = context.getBean("hello", Hello.class);
        String context1 = hello.getContext();
        String name = hello.getName();
        System.out.println(context1);
        System.out.println(name);
    }
}

最后点击运行,控制台就会输出你在bean.xml里面配置的name和context的value值

总结

本次只是对Spring进行一下概念性的阐述以及最基本的使用,后续一步一步的加深,敬请期待

经验分享 程序员 微信小程序 职场和发展