Java教程

Spring基础知识(2)- 创建 Spring 程序

本文主要是介绍Spring基础知识(2)- 创建 Spring 程序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本文将使用 IntelliJ IDEA 和 Apache Maven 创建一个简单的 Spring 程序。在开始之前,确保已经正确搭建了 Spring 开发环境,如何搭建 Spring 开发环境见:Spring基础知识(1)- Spring简介、Spring体系结构和开发环境配置

1. 在 IDEA 上创建 Maven Quickstart 项目

    IntelliJ IDEA:Community Edition for Windows 2020.1.4
    Apache Maven:3.8.1
   
    1) 运行 IDEA
   
        点击菜单 New 创建 Project:
        
        New Project -> Project Type: Maven -> Project SDK: 1.8 -> Check "Create from archtype" -> select "org.apache.maven.archtypes:maven-archtype-quickstart" -> Next

            Name: SpringBasic
            GroupId: com.example
            ArtifactId: SpringBasic

        -> Finish

    2) 生成的项目目录结构和文件

        |-- src
        |   |-- main
        |   |     |-- java
        |   |       |-- com
        |   |            |-- example
        |   |                     |-- App.java
        |   |-- test
        |        |-- java
        |               |-- com
        |                    |-- example
        |                         |-- AppTest.java
        |-- pom.xml

        App.java 的代码:

1             package com.example;
2 
3             public class App {
4                 public static void main( String[] args ) {
5                     System.out.println( "Hello World!" );
6                 }
7             } 

 

2. 编译运行

    1) 可以选择 Java SDK 版本

        在IDE项目列表 -> External Libraries -> <1.8>, 在 "<1.8>" 上点击鼠标右键 跳出菜单,选择 Open Library Settings 菜单项,跳出对话框。
    
        在对话框上 Platform Settings -> SDKS 选择或添加 <1.8>

            Name: 1.8
            JDK home path: select 1.8 SDK or download a SDK

    2) Run App.main()

        Open App.java, click mouse right button, select Run "App.main()"

    3) Edit Configurations

        Click "+" add new configuration -> Select "Application"
            Name: SpringBasic
            Main class: com.example.App
        -> Apply / OK

    4) Click Run "SpringBasic"

        Hello World!

3. 导入 Spring, log4j, slf4j 依赖包

    访问 http://www.mvnrepository.com/,查询 Spring, log4j, slf4j
    
    这里 log4j 和 slf4j 用于把 Spring 输出的 Debug、Warning 等信息保存到 log 文件。

    修改 pom.xml,添加 Spring 依赖:

        <project ... >
            ...

            <dependencies>
                ...
                <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
                <dependency>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                    <version>1.7.36</version>
                </dependency>
                <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
                <dependency>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                    <version>1.7.36</version>
                    <type>pom</type>
                    <scope>test</scope>
                </dependency>
                <!-- https://mvnrepository.com/artifact/log4j/log4j -->
                <dependency>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                    <version>1.2.17</version>
                </dependency>

                <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                    <version>4.3.9.RELEASE</version>
                </dependency>

                <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                    <version>4.3.9.RELEASE</version>
                </dependency>

                <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                    <version>4.3.9.RELEASE</version>
                </dependency>

                <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-jdbc</artifactId>
                    <version>4.3.9.RELEASE</version>
                </dependency>

                ...
            </dependencies>

            ...
        </project>

    在IDE中项目列表 -> 点击鼠标右键 -> Maven -> Reload Project

4. 创建 HelloWorld 类

    在 src/main/java/com/example 目录下,创建 HelloWorld.java,内容如下:

 1         package com.example;
 2 
 3         public class HelloWorld {
 4             private String message;
 5             
 6             public void setMessage(String message) {
 7                 this.message = message;
 8             }
 9 
10             public void getMessage() {
11                 System.out.println("Message: " + message);
12             }
13         }

 

5. 修改 App 类

    在 src/main/java/com/example 目录下,修改 App.java,内容如下:

 1         package com.example;
 2 
 3         // 导入 ApplicationContext 和 ClassPathXmlApplicationContext
 4         import org.springframework.context.ApplicationContext;
 5         import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 
 7         public class App {
 8             public static void main(String[] args) {
 9 
10                 // System.out.println( "Hello World!" );
11 
12                 // Spring IoC 容器创建 Spring Bean
13                 ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
14                 HelloWorld obj = context.getBean("HelloWorld", HelloWorld.class);
15                 obj.getMessage();
16             }
17         }

 

6. 创建 Spring 配置文件 spring-beans.xml

    在 src/main/resources 目录下,创建 spring-beans.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"
                xmlns:context="http://www.springframework.org/schema/context"
                xsi:schemaLocation="http://www.springframework.org/schema/beans
                                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                                http://www.springframework.org/schema/context
                                http://www.springframework.org/schema/context/spring-context-3.0.xsd"
                default-init-method="init"
                default-destroy-method="destroy">

            <bean id="HelloWorld" class="com.example.HelloWorld">
                <property name="message" value="Spring Hello World!" />
            </bean>

        </beans>

    *注:src/main/resources 目录不存在,先创建这个目录,在添加 spring-beam.xml (下文如遇到目录不存在,自行创建)

7. 创建 log4j.properties 文件

    在 src/main/resources 目录下,创建 log4j.properties,内容如下:

        # Define the root logger with appender file
        log4j.rootLogger = DEBUG, FILE

        # Define the file appender
        log4j.appender.FILE=org.apache.log4j.FileAppender
        # Set the name of the file
        log4j.appender.FILE.File=d:\\temp\\spirng-basic_log4j.txt

        # Set the immediate flush to true (default)
        log4j.appender.FILE.ImmediateFlush=true

        # Set the threshold to debug mode
        log4j.appender.FILE.Threshold=debug

        # Set the append to false, overwrite
        log4j.appender.FILE.Append=false

        # Define the layout for file appender
        log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
        log4j.appender.FILE.layout.conversionPattern=%m%n       


8. 运行

    参考 "2. 编译运行"

    运行 App.java,IDEA 控制台中显示信息如下:

        Message: Spring Hello World!



这篇关于Spring基础知识(2)- 创建 Spring 程序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!