IntelliJ IDEA中创建Spring项目(1)

一、创建工程
1.创建Spring项目
在这里插入图片描述
2.工程自动下载Spring框架所需要的的jar包
在这里插入图片描述
https://repo.spring.io/libs-release-local/org/springframework/spring/5.2.3.RELEASE/
如果遇到网络问题,可以从这里下载后,配置进工程
在这里插入图片描述
在这里插入图片描述
二、测试
helloSpring

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

Main

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

public class Main {
    public static void main(String[] args){
        //传统创建方法
        helloSpring hello = new helloSpring();
        hello.setName(" old method");
        hello.sayHello();

        //采用Spring框架
        //创建Spring IOC容器对象 Inversion of Control 控制反转
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        //从ioc容器获取bean对象
        helloSpring HelloSpring = (helloSpring)context.getBean("helloSpring");
        HelloSpring.sayHello();
    }
}
Spring-config.xml

在这里插入图片描述
输出结果
在这里插入图片描述
总结:
创建实例对象以及设置对象的属性,也就是说我们可以把对象的创建和管理工作交给Spring去完成,不需要自己去new对象,也不要去设置对象的属性,只要写好Spring的配置文件,Spring就可以帮我们去做,当我们需要对象的时候,直接去找Spring去要就行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章