HelloSpring

发布时间 2023-05-07 18:47:07作者: YE-

别提了,学了一会儿黑马的SSM框架,很懵
听了女朋友的建议,改换遇见狂神说的Spring的讲解课程了

跟着狂神说,编写了最初的程序HelloSpring程序

第一步,Maven导入Spring和junit的依赖

第二步,创建pojo文件夹,导入一个实体类作为练习

记得需要鼠标右键,选择ptg Java Bean(可以自动创建下面那一堆)

第三步,使用Spring创建对象,在Spring这些都称为Bean

等价于 类型 变量名称 = new 类型();
Hello hello = new Hello();

  id = 变量名
 class = new 的对象;
property相当于给对象中的属性设置一个值

第四步,书写测试类

1.获取Spring的上下文对象!ClassPathXmlApplicationContext是固定用法,调用.xml文件,我只会用,具体是什么意思我还不太理解

2.我们的对象现在都在Spring中的管理了,我们要使用,直接从里面取出来就可以了

测试类运行截图

在这里放一些代码吧

mytset.java

import org.example.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class mytset {
    public static void main(String[] args) {
        /*获取Spring的上下文对象!*/
        ApplicationContext atc = new ClassPathXmlApplicationContext("Beans.xml");
        //我们的对象现在都在Spring中的管理了,我们要使用,直接从里面取出来就可以了
        Hello hello = (Hello) atc.getBean("hello");
        System.out.println(hello.toString());


    }
}

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 http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--使用Spring创建对象,在Spring这些都称为Bean-->
    <!--
        <bean></bean> 等价于 类型 变量名称 = new 类型();
        Hello hello = new Hello();

        id = 变量名
        class = new 的对象;
        property相当于给对象中的属性设置一个值
    -->

        <bean id="hello" class="org.example.pojo.Hello">
        <property name="str" value="spring"></property>

        </bean>

</beans>