IEDA环境搭建

开发环境:
IntelliJ IDEA 2019.2.4
JRE: 1.8.0_91-b14 amd64


用Spring输出Hello spring

创建Spring项目

初次打开IDEA直接点击Create New Project

idea springboot java没有run idea2021没有spring_spring


若是已经创建了项目可以在点击左上角的File选择new→project,然后勾选create empty spring-config.xml自动生成spring配置文件

idea springboot java没有run idea2021没有spring_spring_02


这时候等待IDEA自动下载项目所依赖的jars,创建好项目后会看到一个Spring的配置文件

idea springboot java没有run idea2021没有spring_spring_03

输出Hello spring步骤

1.创建一个HelloWorld类

public class HelloWorld {
    private String name;
  
    public void setName(String name){
        this.name=name;
    }
    public void sayHello()
    {
        System.out.println("Hello "+name);
    }
}

2.配置文件

<?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-->
    <bean id="helloWorld" class="HelloWorld">
         <property name="name" value="Spring"></property>
    </bean>
</beans>

3.Main中写入内容

public class Springmain {
    public static void main(String[] arges)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

        HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
        helloWorld.sayHello();
    }
}

运行结果:

idea springboot java没有run idea2021没有spring_xml_04


至于Spring到底干了些什么,与我们直接创建一个实例对象,再设置实例对象name的属性,最后调用sayHello方法有什么区别,我们可以使用断点调试来看看:

首先修改一下HelloWorld类

idea springboot java没有run idea2021没有spring_spring_05

在此处设置断点

idea springboot java没有run idea2021没有spring_xml_06

之后进入Debug模式,可以看到在创建了一个Spring的IOC容器对象的时候就已经调用了HelloWorld的构造函数和setName方法。也就是说,Spring帮我们完成了实例化对象的创建以及对象属性的设置,这些步骤只需要我们写好配置文件,其余的交给Spring去做就好了!