HelloSpring

声明

本文为其他博主原创文章整合,仅用作个人学习,特此声明

参考文章链接

(3条消息) B站 - 狂神 - Spring5课堂笔记_夜里的雨的博客-CSDN博客_狂神spring5笔记

3、HelloSpring

在父模块中导入jar包

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>5.2.7.RELEASE</version>
</dependency>

pojo的Hello.java

public class Hello {

	private String str;
	
	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}
	
	@Override
	public String toString() {
		return "Holle [str=" + str + "]";
	}
}

在resource里面的xml配置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
        https://www.springframework.org/schema/beans/spring-beans.xsd">


    <!--在Spring中创建对象,在Spring这些都称为bean
    	类型 变量名 = new 类型();
    	Hello hello = new Hello();
    	
    	bean = 对象(hello)
    	id = 变量名(hello)
    	class = new的对象(new Hello();)
    	property 相当于给对象中的属性设值,让str="Spring"
    -->
    
    <bean id="hello" class="pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>

重点理解代码中的注释

image-20220611105739756

测试类MyTest

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

import pojo.Hello;

public class MyTest {

	public static void main(String[] args) {
		//获取Spring的上下文对象(这行代码是写死的)
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
		//我们的对象现在都在spring·中管理了,我们要使用,直接取出来就可以了
		Hello hello = (Hello) context.getBean("hello");
		System.out.println(hello.toString());
	}
}


程序写完了,思考一个问题吧

IOC:对象由Spring 来创建,管理,装配!

举一个很简单的例子如下

原来这套程序是:你写好菜单买好菜,客人来了自己把菜炒好招待,就相当于你请人吃饭
现在这套程序是:你告诉楼下餐厅,你要哪些菜,客人来的时候,餐厅把做好的你需要的菜送上来
IoC:炒菜这件事,不再由你自己来做,而是委托给了第三方__餐厅来做

此时的区别就是,如果我还需要做其他的菜,我不需要自己搞菜谱买材料再做好,而是告诉餐厅,我要什么菜,什么时候要,你做好送来

posted @ 2022-06-11 11:04  无关风月7707  阅读(66)  评论(0编辑  收藏  举报