在IntelliJ IDEA中创建Spring项目

975 阅读2分钟

在IntelliJ IDEA中创建Spring项目

1、点击「Create New Project」

image.png

2、选择「Spring」,Libraries选择默认的「Download」即可,默认勾选的「Create empty spring-config.xml」不要动。然后点击「next」

image.png

3、设置「Project name」,即你的项目名字。其他的使用默认生成的即可。然后点击「next」

image.png

注:IntelliJ IDEA中的project相当于eclipse中的workspace,而module才相当于一个project,所以我们不需要创建workspace,IntelliJ IDEA默认也会给你创建一个module。

4、IntelliJ IDEA会帮我们自动下载好Spring所需要的jar包,waiting...

image.png

5、等待下载完毕,Spring所需要的jar包和配置文件均会自动生成好

image.png

一个简单例子理解Spring框架

1、首先创建一个HelloWorld类,有一个name属性,还有一个sayHello()方法,还有一个setter()方法用来设置name属性。

public class HelloWorld {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void sayHello() {
        System.out.println("Hello " + this.name);
    }
}

2、不使用框架,调用方法

在我们不使用框架的时候,也就是平常的编程中,我们要调用sayHello这个方法,可以分为3步: 
(1)创建一个HelloWorld的实例对象 
(2)设置实例对象的name属性 
(3)调用对象的sayHello()方法

@Test
public void test() {
    HelloWorld helloWorld = new HelloWorld();
    helloWorld.setName("No Spring");
    helloWorld.sayHello();
}

运行程序,可以看到方法成功调用:

image.png

3、使用Spring,首先在Spring配置文件spring-config.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="com.spring.demo.HelloWorld">
        <property name="name" value="Spring"></property>
    </bean>
</beans>

4、使用Spring框架,调用方法

使用Spring框架调用sayHello()方法的时候也需要3个步骤:

(1)创建一个Spring的IOC容器对象

(2)从IOC容器中获取Bean实例 

(3)调用sayHello()方法

@Test
public void testSpring() {
    // 1、创建一个Spring的IOC容器对象
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
    // 2、从IOC容器中获取Bean实例`
    HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
    // 3、调用sayHello()方法
    helloWorld.sayHello();
}

这和之前完全不一样了,我们运行看下:

image.png

5、解释说明一下

第一次使用Spring,我们明明没有创建HelloWorld的实例对象,只是配置了下Spring的配置文件,怎么就能得出正确的结果呢?这是因为我们使用了Spring的IOC功能,把对象的创建和管理的功能都交给了Spring去管理,我们需要对象的时候再和Spring去要就行。

6、那么Spring什么时候new的对象呢

先修改一下HelloWorld类

image.png

添加断点进入Debug模式。可以看到,当执行到第一步创建IOC容器对象的时候就调用了HelloWorld类的构造方法和setter方法。

image.png