java搭建Spring框架

文章目录

  • java搭建Spring框架
  • 前言
  • 一、安装IntelliJ IDEA
  • 二、搭建Spring项目
    • 1.新建一个项目
    • 2. 导入Spring
    • 3.运行HelloWorld!


前言

本篇文章主要是在IntelliJ IDEA上搭建Spring项目,并简单运行Hello Word!,方便学习交流。


一、安装IntelliJ IDEA

这里主要介绍怎么搭建Spring项目,安装idea不再介绍,具体可以百度或者联系我。

二、搭建Spring项目

1.新建一个项目


生成的目录结构如下所示:

2. 导入Spring



然后在str目录下,新建一个xml文件和两个java文件。

文件名可以自己随意命名,在这里我们命名为Beans,继续在str目录下新建两个Hello World.Java和MainApp.java文件,目录结构如下

3.运行HelloWorld!

MainApp.java代码:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
        obj.getMessage();
    }
}

Hello World代码:

public class HelloWorld {
    private String message;
    public void setMessage(String message){
        this.message  = message;
    }
    public void getMessage(){
        System.out.println("Your Message : " + message);
    }
}

Beans.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework/schema/beans"
       xmlns:xsi="http://www.w3/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework/schema/beans http://www.springframework/schema/beans/spring-beans.xsd">
    <bean id="helloWorld" class="HelloWorld">
        <property name="message" value="Hello World!"/>
    </bean>
</beans>

运行结果:

更多推荐

IntelliJ IDEA(2021.1)上搭建Spring框架