浅谈Sping

一、如何使用IDEA创建一个Spring项目

1、创建一个Maven项目

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

2、添加spring依赖

在这里插入图片描述
spring依赖:

<dependencies>
   <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
  
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
</dependencies>

添加成功之后的样子:
在这里插入图片描述

注意了!!!! 在pom.xml中添加了spring依赖之后,在< version>版本号< /version>
标签的版本号处会出现报红情况,出现红色波浪线,我上面没出现报红情况是因为我已经配置好了maven国内源了。那么你报红该怎么办??参考如下解决方案:

2.1报红解决方案

2.1.1、点击右侧的Maven标志

在这里插入图片描述

2.2.2、reload

在这里插入图片描述
reload的过程中,IDEA的右下角会有一个进度条,进度条加载完成之后,项目中的pom.xml文件不再报红,表示项目加载成功。(但是,如果创建的启动类去进行代码测试,运行报错的话,此时表示Maven也还是没配置成功。这时候该怎么办,往下看。)

3、启动类(测试spring项目是否能运行,maven是否配置成功)

在这里插入图片描述

3.1 启动类的代码运行不成功,或者reload之后仍旧报红,那么此时该怎么办??

3.1.1、配置国内源

在这里插入图片描述
下面,我以当前创建的项目为例,配置Maven国内源。
在这里插入图片描述
做完这一步,点击reload,看看pom.xml是否还报红,或者项目能否运行成功。不成功的话,继续做下一步。
在这里插入图片描述
使用快捷键(Windows + R)打开cmd,在cmd里面输入复制的路径,然后找到settings.xml文件,使用记事本、vsCode打开settings.xml文件都得,在settings.xml文件里找到< Mirrors> 标签,在里面添加如下的< mirror>标签。

<mirror>
        <id>alimaven</id>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
        <mirrorOf>central</mirrorOf>
    </mirror>

注意了 如果你在复制的目录下面没有找到settings.xml这个文件,就在复制的路径下面新建一个settings.xml文件。将下面的内容复制进去(复制了这个文件,就不用再添加< mirror>标签了,里边自带了):

<?xml version="1.0" encoding="UTF-8"?>
 
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
 
<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single
 |                 user, and is normally provided in
 |                 ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all
 |                 Maven users on a machine (assuming they're all using the
 |                 same Maven installation). It's normally provided in
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start
 | at getting the most out of your Maven installation. Where appropriate, the
 | default values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
 
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
 
 
  <!--<localRepository>C:/Users/Administrator/.m2/repository</localRepository>  -->
  
  <localRepository>E:\Maven\repository</localRepository>
 
  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set
   | to false, maven will use a sensible default value, perhaps based on some
   | other setting, for the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->
 
  <!-- offline
   | Determines whether maven should attempt to connect to the network when
   | executing a build. This will have an effect on artifact downloads,
   | artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->
 
  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when
   | resolving plugins by their prefix, i.e. when invoking a command line like
   | "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not
   | already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>
 
  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to
   | the network. Unless otherwise specified (by system property or command-
   | line switch), the first proxy specification in this list marked as active
   | will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>
 
  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used
   | within the system. Authentication profiles can be used whenever maven must
   | make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a
     | particular server, identified by a unique name within the system
     | (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR
     |       privateKey/passphrase, since these pairings are used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->
 
    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>
 
  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote
   | repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving
   | certain artifacts. However, this repository may have problems with heavy
   | traffic at times, so people have mirrored it to several places.
   |
   | That repository definition will have a unique id, so we can create a
   | mirror reference for that repository, to be used as an alternate download
   | site. The mirror site will be the preferred server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository.
     | The repository that this mirror serves has an ID that matches the
     | mirrorOf element of this mirror. IDs are used for inheritance and direct
     | lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
 
    <mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>central</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </mirror>
  </mirrors>
 
 
 
  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways,
   | and which can modify the build process. Profiles provided in the
   | settings.xml are intended to provide local machine-specific paths and
   | repository locations which allow the build to work in the local
   | environment.
   |
   | For example, if you have an integration testing plugin - like cactus -
   | that needs to know where your Tomcat instance is installed, you can
   | provide a variable here such that the variable is dereferenced during the
   | build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One
   | way - the activeProfiles section of this document (settings.xml) - will be
   | discussed later. Another way essentially relies on the detection of a
   | system property, either matching a particular value for the property, or
   | merely testing its existence. Profiles can also be activated by JDK
   | version prefix, where a value of '1.4' might activate a profile when the
   | build is executed on a JDK version of '1.4.2_07'. Finally, the list of
   | active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to
   |       specifying only artifact repositories, plugin repositories, and
   |       free-form properties to be used as configuration variables for
   |       plugins in the POM.
   |
   |-->
 
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated
     | using one or more of the mechanisms described above. For inheritance
     | purposes, and to activate profiles via <activatedProfiles/> or the
     | command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a
     | consistent naming convention for profiles, such as 'env-dev',
     | 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. This
     | will make it more intuitive to understand what the set of introduced
     | profiles is attempting to accomplish, particularly when you only have a
     | list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and
     | provides a JDK-specific repo.
     
    <profile>
      <id>jdk-1.4</id>
      <activation>
        <jdk>1.4</jdk>
      </activation>
      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->
 
 
    <!--
     | Here is another profile, activated by the system property 'target-env'
     | with a value of 'dev', which provides a specific path to the Tomcat
     | instance. To use this, your plugin configuration might hypothetically
     | look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone
     |       set 'target-env' to anything, you could just leave off the
     |       <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>
      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>
      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
    
    <profile>    
        <id>jdk-1.8</id>    
         <activation>    
            <activeByDefault>true</activeByDefault>    
            <jdk>1.8</jdk>    
          </activation>    
        <properties>    
            <maven.compiler.source>1.8</maven.compiler.source>    
            <maven.compiler.target>1.8</maven.compiler.target>
            <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> 
        </properties>    
    </profile>
 
  </profiles>
  
  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

做完以上的步骤,回到IDEA界面,点击reload。如果pom.xml还报红,或者项目运行不成功。继续做下面这步。

3.1.2 配置和检查settings

1、删除本地maven仓库的jar包。
在这里插入图片描述
将以上红框里的路径复制,在cmd中打开,按住快捷键 ctrl + A 将目录repository里的所有文件删除。再回到IDEA界面点击reload。一般来说,做到这一步,Maven都能配置成功,项目都能运行起来。那到底Spring项目怎么样才算是运行成功??Maven国内源才算是配置成功??有两方面:

1、在这里插入图片描述

2、在这里插入图片描述

走到这,一般来说,大部分人的maven都能配置成功,如果你的还配置不成功,间隔一段时间,重复 3.1.1步骤和3.1.2步骤至少3遍以上。

二、为什么要学习框架?

1、面试会问,工作天天用到(Java研发岗、测开岗、测试岗)。
2、使用框架快捷开发项目,提高效率。(框架的核心是解耦合)。

三、什么是spring?

          spring 也叫 spring framework(Spring 框架),它是⼀个开源框架,有着活跃⽽庞⼤的社区,这就是它之所以能⻓久不衰的原因。

          Spring ⽀持⼴泛的应⽤场景,它可以让 Java 企业级的应⽤程序开发起来更简单。Spring的核心是Ioc(Inversion of control) 控制反转和DI(Dependency Injection)依赖注入。

          用一句话概括Spring:Spring是一个拥有众多工具、方法的loc容器

3.1、什么是ioc?

          ioc(Inversion of control),叫做控制反转,指的是对 类或者对 对象的生命周期进行控制反转。

          传统开发中,类A想要使用类B的某个方法、属性的话,类A就需要在自己的类里new一个类B,这就表明类B的生命周期是由程序员控制的,当程序员不想使用类B里面的方法、属性了,程序员就把类B对象置为null就行了。所以传统开发中,对象生命周期的控制权是在程序员手里的。

          但是到了Spring框架里,类A想要使用类B时,不再需要程序员通过new 类B对象来控制类B的生命周期了,而是直接从Spring框架里取类B对象来使用就行了。这是因为控制反转了,对象(bean)存在Spring里了,此时对象的生命周期就由Spring管理着,想要使用bean时,直接从Spring里取然后拿来用就行了。那么我们为什么要使用Spring来托管bean呢??其实是为了进行代码的解耦合。

3.1.1.1 使用一个例子来深刻了解ioc

以车为例子,一辆车(Car),其大小依赖于车身(Framework),车身大小又依赖于底盘(Bottom),底盘又依赖与轮胎(Tire)大小。现在我使用传统开发的方式书写代码来实现该例子之间的依赖关系。

Car

public class Car {
    public Framework framework;
    public Car(int size){
        framework = new Framework(size);
    }
    public void init(){
//        依赖车身
        System.out.println("执行了Car的init()方法!");
        framework.init();
    }
}

Framework

public class Framework {
    public Bottom bottom;
    public Framework(int size){
        bottom = new Bottom(size);
    }
    public void init(){
//        依赖底盘
        System.out.println("执行了Framework的init()方法!");
        bottom.init();
    }
}

Bottom

public class Bottom {
    public Tire tire;
    public Bottom(int size){
        tire = new Tire(size);
    }
    public void init(){
        //依赖车轮
        System.out.println("执行了Bottom的init()方法!");
        tire.init();
    }
}

Tire

public class Tire {
    public int size;

    public Tire(int size){
        this.size = size;
    }
    public void init() {
        System.out.println("车子的轮胎大小:" + size );
    }
}

APP(测试类)

public class APP {
    public static void main(String[] args) {
        Car car = new Car(20);
        car.init();
    }
}

测试类的执行结果:
在这里插入图片描述
从上述执行结果可知,相互依赖的类之间,一方想使用自己需要的类里面的方法、属性时,通过new对象的方法去使用,例如Car类依赖Framework类,因此Car在自己的构造方法里通过new Framwork 去使用Framework里的方法、属性。其他类也是一样。但是,这样的代码耦合度太高。为什么说耦合度高??往下看。
在这里插入图片描述
Tire类还是一样的代码,只不过此时的车,用户需要自定义颜色,所以在Tire类中新加了一个color属性,此时,代码出现这样的报错---->1 related problem。

这时依赖于Tire类的Bottom类,出现了报错问题。
在这里插入图片描述
整个调用链都需要修改,所以说代码耦合度太高了,写代码需要讲究高内聚,低耦合,因此需要使用ioc进行解耦合。

接下来使用ioc进行上述例子代码的实现。
Car

public class Car {
    public Framework framework;
    public Car(Framework framework){
        this.framework = framework;
    }
    public void init(){
        //依赖车身
        System.out.println("执行了Car的init()方法!");
        framework.init();
    }
}

Framework

public class Framework {
    public Bottom bottom;
    public Framework(Bottom bottom){
        this.bottom = bottom;
    }
    public void init(){
//        依赖底盘
        System.out.println("执行了Framework的init()方法!");
        bottom.init();
    }
}

Bottom

public class Bottom {
    public Tire tire;
    public Bottom(Tire tire){
        this.tire = tire;
    }
    public void init(){
        //依赖轮胎
        System.out.println("执行了Bottom的init()方法!");
        tire.init();
    }
}

Tire

public class Tire {
    public int size;
    public Tire(int size){
       this.size = size;
    }
    public void init(){
        System.out.println("车子的轮胎大小:" + size);
    }
}

APP(测试类)

public class APP {
    public static void main(String[] args) {
        Tire tire = new Tire(20,"黑色");
        Bottom bottom = new Bottom(tire);
        Framework framework = new Framework(bottom);
        Car car = new Car(framework);
        car.init();
    }
}

测试类的执行结果:

在这里插入图片描述
使用ioc实现的代码里,即使Tire类新增color属性,依赖Tire类的Bottom类也并不需要也去新增一个color属性,因此依赖Bottom的Framework类也不需要去改变,相反的,在APP测试类里可以看出,创建Car实例之后,还不行,必须先创建Framework的实例,而对于Framework来说,需要先创建Bottom实例才行,对于Bottom来说,需要先创建Tire实例才行,跟传统开发比,此时整个调用链都发生了改变。

这就表明,即使改变时Tire类的结构,其他类的代码都不需要进行改变,说明此时代码的耦合度降低了。因为在ioc代码里,不再进行new操作,而是使用了依赖注入的手段,在程序调用时,动态的将对象注入进来。
在这里插入图片描述
在Spring中,ioc(控制反转)是一种设计思想,DI(依赖注入)是一种实现方式。

  • 16
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值