javaEE进阶 - Spring 创建 和 使⽤ - 细节狂魔

x33g5p2x  于2022-07-10 转载在 Java  
字(13.7k)|赞(0)|评价(0)|浏览(363)

前言

经过前面Spring 核心 与 设计思想的学习,我们已经知道了:Spring 就是一个包含众多工具方法的 IoC 容器。
既然是容器,那额它就具有两个核心功能:
1、将对象(Bean) 存储到容器中
2、从容器中将对象(Bean)去出来

本文主要讲解的重点:

1、创建项目
2、将对象存储到 Spring
3、从 Spring中取出对象

1、创建 Spring 项目

接下来使用 Maven 方式 来创建一个 Spring 项目。
创建 Spring 项目 和 Servlet 相似。
总共分为以下 3 步:
1、创建一个普通 Maven 项目
其实 Spring Boot 也是基于 Maven 来实现的。
只不过 Spring 需要我们自己去创建,而 Spring Boot 直接内置了。

2、在 Maven 项目中,添加 Spring 框架支持(spring-context,spring-beans)

3、创建一个启动类,并添加 main 方法。
其实第三步是一个非必要操作,但是我们后面需要去测试 Bean(对象)的存入 与 取出的。
因此,我们需要一个可以测试的类,
故:需要创建一个启动类(测试的类)和 main,而不是依靠 Tomcat 的错误提示。
如果你是创建的一个 Spring Web,或者 Spring MVC,那需要依靠Tomcat。
而我们现在创建的项目是 Spring Core 。
core 核心项目,也就是最基础的核心项目。
所以,我们不需要依靠 Tomcat,就一个类就可以了。

注意!我们现在学习的是 Spring,不是 Spring Boot。
Spring 是在 Spring Boot 之前的框架。
因此,Spring 操作起来。没有像 Spring Boot 那么方便!
难度,和 servlet 差不多。

凡事都要一个过程。
最初的框架,并没有那么好用。
总有一个发展的过程。
很显然,Spring 属于前者,Spring Boot 属于后者。

1.1、创建一个 Maven 项目

1.2、在 Maven 项目中,添加 Spring 框架支持(spring-context,spring-beans)

我都给你们准备好了。
直接复制粘贴到 pom.xml 文件中即可。

<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>

另外,一定要配置 国内的源!!!!!
就算此时不出问题,以后也会出问题!

如果你还是使用默认的国外源
尤其是创建 Spring Boot 项目,引入依赖的时候,及其容易翻车!

settings.xml 的配置。【这是阿里维护的一个国内源】

<?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.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: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</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>
        <id>alimaven</id>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        <mirrorOf>central</mirrorOf>        
      </mirror>
    <!-- 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>
     -->
  </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>
    -->
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

配置好了,可以用 VSCode ,来打开这个源。
来查看一下,有没有下图中的内容。
有,就说明国内源,完全配置好了。【这个部分需要你往下翻】

如果你有 settings.xml 文件,就把上面框选的部分,手动拷贝进去。
拷贝的位置,就跟框选的位置是一样的。
我也给你准备好了。。。。【就在下面】
PS:如果没有配置过的朋友,你就直接按照上述步骤,去弄就行了。

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

还没有完,此时我们设置的,只是针对当前项目。
如果你在创建一个项目。虽然不需要重新配置。
但是,需要重新勾选。

更简便的方法就是提前针对新项目进行设置,看下图。

另外,还有一个特殊的情况,在我们配置化好了之后。
仍然,下载依赖失败,或者代码运行有问题。
这是因为 你的 jar包(依赖)下载缺失,锁导致的问题。

如果你还是失败,那就是你自己网络的问题了!
换个网吧,孩纸。。

1.3、创建一个启动类 和 main 方法

在 java目录下,创建一个 Java类。
名字随意,至于类的内容,暂时写成下方中的内容

直接运行程序,如果成功打印。
说明配置没问题。

2、将 Bean 对象存储到容器(Spring)中

要实现这个目的,我们需要 两个 或 三 个 步骤。
为什么,这里要有个或呢?
换个说法:到底是2个,还是3个步骤呢?
这个是取决于 你 添加的这个 Bean 对象,是第一次添加,还是非第一次添加。

如果是 第一次添加,那么,有三个步骤:
1、现在 Spring 项目中 添加配置文件【非第一次,此步骤可以省略】

2、存储 Bean 之前,先得有 Bean 才⾏,因此先要创建⼀个 Bean。

3、在配置文件中,将需要保存到 spring中的 bean 对象进行注册。

2.1、现在 Spring 项目中,添加配置文件。【如果是第一添加Bean对象】

和 Servlet 宏配置 web,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">

</beans>

将上述的 代码进行拷贝,进行如下操作。

2.2、存储 Bean 之前,先得有 Bean 才⾏,因此先要创建⼀个 Bean。

所谓的 Bean 对象,其实就是 Java 中的普通类。
只不过 权限是由 spring 所持有。

此时,我们所要做的是:将 这个 Bean 对象 存入 spring。
然后,在后面的时候,从spring当中 读取到 User,然后调用里面的 方法。

2.3、在配置文件中,将需要保存到 spring中的 bean 对象进行注册。

我们需要对 spring-config.xml 配置文件,进行如下操作。

另外,再补充一点:id 的值,可以与 类名 不相同的。
只所以这样去写,是因为:这样写,很规范。

这样写,虽然可以。
但是!我们还是要养成良好的代码习惯,尽量符合规范。
将 id的值,要能描述业务场景。
别人看到这个名字,就知道这个 bean 对象是哪一个,是干什么的。

不过在当前场景,也是完全可以的。
另外,id 的值和 类名,完全一样也是可以的。

这里,再告诉你一个细节,规范一般要求: id 是 小驼峰。
所以,我一开始 写的 开头字母是小写。

因此,这么写,是最好的!
其实这个规范,是由于引入 jdk所导致的。
id 的取名规则,是根据 Java 方法 的命名规则来的。
这里现有这样的一个概念,
后面到了合适的时候,会仔细讲 为什么 id 的取值是小驼峰结构。

如果你想要注入 多个 bean 对象,你就创建读个 bean 标签就行了。
至于里面的 id 和 class 值,你们应该都会。

3、从 Spring 中,将 Bean 对象读取出来。

读取操作,可分为三步:
1、先得到 spring 上下文对象
就是你要读取 Spring 里面的东西,需要先得到 Spring。
你可以这么认为:上下文对象 等价于 Spring

2、得到Spring上下文对象之后,再通过 上下文对象提供的方法,获取 我们自己需要使用的 bean 对象

3、拿到 bean 对象之后,就可以调用 里面的方法。

拿到 bean 对象之后,就可以使用 bean 对象了。

3.1、得到 Spring 上下文对象

3.2、通过 上下文对象提供的方法,获取 我们自己需要使用的 bean 对象

3.3、拿到 bean 对象之后,就可以调用 里面的方法。

此时,获取到 bean 对象,也就是 User 类的对象。
里面包含着,此次我们需要调用的 sayHi 方法。

这就是 Spring 中最基础的操作。

注意事项

ClassPathXMLAppLicationContext 类中的参数,一定要 配置文件名称一致!

比如:将 spring-config 写成了 spring comfig。
把 config 中 n 写成 m 了。

另外,告诉你们一个快速锁定异常位置的技巧。
Ctrl + F : 搜索功能

附赠小技巧:如果你处理了该代码,运行还是出错。
而且,出问题的还是这部分,但是,就是改了,没效果。
首先,你要明白:这不是你的问题!
这是因为 编辑器 产生运行缓存。
你的运行结果,它直接照搬 上次运行出错的状态。
我们需要做的就是:将 target 目录删除,重新执行程序即可。

准确来说:target目录,和 servlet 一样,就是 JVM 运行的目录。
这个目录,是自动生成的。
根据项目中的 源代码 和 资源文件,自己去生成一个 target文件的。
而且,你展开 target 目录,就会发现 和 上面的目录结构,完全是一样的。

Bean 的 Id 要⼀⼀对应

拓展

除了 ApplicationContext 之外,我们还可以使⽤ BeanFactory 来作为 Spring 的上下文

BeanFactory -> Bean Factory(Bean对象工厂)

既然 BeanFactory 可以达到 ApplicationContext 相同的效果。
那么,这两者之间又有什么区别?
这可以非常经典的面试题哦!!!!!

ApplicationContext 与 BeanFactory 的区别

下面,我们来通过代码来模拟验证一下。
BeanFactory 究竟是不是 懒加载
ApplicationContext 是不是 一次性将 bean 对象,全部加载。

getBean ⽅法的更多⽤法

getBean() ⽅法有很多种重载⽅法,我们也可以使⽤其他⽅式来获取 Bean 对象.

1、使用 bean id 获取 bean对象。

这个就是我们上面所使用的方法

2、根据 bean 的 类型 来获取 bean对象

怎么做呢?
方法还是 getBean 方法,只是传的参数不同,

3、第三种写法,属于 第一种 和 第二种 的 结合。

使用 Bean 的 id 和 对象类型(两个参数)来锁定唯一的对象(bean)。

第三种写法,是最推荐的!
因为 它 最稳。

总结

本文重点有三大点:
1、操作容器之前,先要有容器,所以先要得到容器。
  1.1、创建 嘛呢呗项目
  1.2、添加 Spring 框架支持,引入 spring-context 和 spring-beans 依赖
  1,3、创建一个启动类 和 main方法

2、存对象
  2.1、创建 Bean(普通类)
  2.2、将 Bean 注册(配置)到 spring-config.xml 中。【bean标签】

3、取对象
  3.1、得到 Spring 上下文对象,并读取到 Spring 的配置文。【ApplicationContext】
  3.2、获取某一个bean(对象)
  3.3、使用 Bean(对象)

操作流程图

相关文章

微信公众号

最新文章

更多