2 Spring起步练习

2019-02-27  本文已影响0人  陶然然_niit

1 准备Maven环境,并在IDEA中进行配置

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

2 建立Java项目,并添加Maven支持

3在pom文件中添加SpringContext依赖

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

等待下载完毕,展开右侧的Maven选项卡,会出现如图所示的依赖


Maven视图

再回到本地Maven仓库观察,发现自动下载了很多的依赖


本地Maven仓库

4 新建package,编写HelloWorld类

package com.spring.hello;

public class HelloWorld {
    public String getHello() {
        return "Hello World";
    }
}

5 在resources根路径下创建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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
   <!--配置一个HelloWorld类的bean-->
    <bean id="helloWorld" class="com.spring.HelloWorld"/>
</beans>

6 编写主类,并运行

package com.spring;

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

public class HelloWorldApp {
    public static void main(String[] args) {
        //1 读入配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("/beans.xml");
        //2 读取配置好的bean
        HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
        //3 运行helloWorld的方法
        System.out.println(helloWorld.getHello());
    }
}

运行结果:


运行结果

红字的原因是因为没有使用日志

7 项目结构

项目结构
上一篇 下一篇

猜你喜欢

热点阅读