我的第一个Spring程序_HelloSpring

我的第一个Spring程序_HelloSpring

  1. 导入spring-webmvc依赖包
  2. 创建Hello实体类
  3. 创建applicationContext.xml配置类
  4. 实例化容器

1、导入Spring 依赖包,为了方便可直接导入spring-webmvc的依赖

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

2、创建Hello实体类

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

	public void setStr(String str) {
		this.str = str;
	}

	@Override
	public String toString() {
		return "File [str=" + str + "]";
	}
	
}

3、创建 applicationContext.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">

    <!--java写法:Hello hello = new Hello();	hello.setString("HelloSpring!");
		id据相当于hello对象
		class就相当于new的类
		property就相当于给对象赋值
	-->
    <bean id="hello" class="Hello">  
        <!-- collaborators and configuration for this bean go here -->
        <propterty name="str" value="HelloSpring!" />
    </bean>

</beans>

4、实例化容器

public class MyTest {
    
    public static void main(String[] args) {
    //获取Spring的上下文对象,对象是Spring创建的
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //我们的对象现在都在Spring中的管理了,我们要使用,直按去里面取出来就可以!
    Hello hello = (Hello) context.getBean("hello");
	System.out.println(hello.toString());
}

总结:

这个过程就叫控制反转:
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的.
反转:程序本身不创建对象,而变成被动的接收对象.
依赖注入:就是利用set方法来进行注入的.
IOC是一种编程思想,由主动的创建变成被动的接收.

猜你喜欢

转载自www.cnblogs.com/abc991314/p/13406741.html