HelloSpring.
目录结构
环境搭建及实现.
- 导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
2.新建实体类 Hello
(这里使用Lombok构建实体类)
@Data
public class Hello {
private String content;
}
- 新建
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
java new 对象写法
类型 变量名 = new 类型();
Spring new 对象写法
id = 变量名
class = new的对象类型
property 为属性设置一个值 name是属性名 value是基本类型、String类型的具体值 ref是引用Spring容器中已经创建好的对象(id对应的值)
-->
<bean id="hello" class="pojo.Hello">
<property name="content" value="Hello,Spring!"/>
</bean>
</beans>
- 编写测试
public class MyTest {
@Test
public void hello(){
//获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//从上下文中获取Hello对象
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.getContent());
}
}
- 结果展示
小结.
- 我们并没有去手动new对象
- 对象是Spring创建的,其属性也是有Spring容器设置的
- Spring就是那个第三方
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring创建的
反转:程序本身不创建对象,而变成被动的接收对象。
依赖注入:就是利用set方法来进行注入的
IOC是一种编程思想,由主动的编程变成被动的接收
对象由Spring创建,管理,装配