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>
重点理解代码中的注释
测试类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:炒菜这件事,不再由你自己来做,而是委托给了第三方__餐厅来做
此时的区别就是,如果我还需要做其他的菜,我不需要自己搞菜谱买材料再做好,而是告诉餐厅,我要什么菜,什么时候要,你做好送来
分类:
Day75
, spring5入门随笔
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律