首页 > 编程语言 > 详细

用Spring写一个HelloWorld

时间:2020-12-11 16:42:23      阅读:37      评论:0      收藏:0      [点我收藏+]

1、在IDEA中安装Spring插件

点击File--settings--Plugins,搜索“Spring”,安装Spring Assistant。

技术分享图片

新建Spring项目

1、新建项目:New--Project,选择Spring

技术分享图片

 

 

 IDEA有一个好处,当你创建spring项目时,它会自动下载所需要的spring包

2、右键src,创建一个包(Package),名字叫作"hello"吧。

3、在hello包下创建两个class源文件:HelloWorld.javaMainApp.java

其中,HelloWorld.java中写入:

package hello;

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

 MainApp.java中写入:

package hello;
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();
    }
}

 上面MainApp.java文件里,有一个Beans.xml

技术分享图片

 

 

 这是一个配置文件,需要手动创建它。

4、创建配置文件Beans.xml

右键src--New--XML Configuation File--Spring Config

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

    <bean id="helloWorld" class="hello.HelloWorld">
        <property name="message" value="Hello World!"/>
    </bean>

</beans>

class 属性表示需要注册的 bean 的全路径,这里就是HelloWorld.java的文件路径

id 则表示 bean 的唯一标记。

这里的value中的值,就是输出到屏幕上的内容。

总结:

技术分享图片

用Spring写一个HelloWorld

原文:https://www.cnblogs.com/yabc/p/14120708.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!