spring系列-springhello

springhello程序

先写个实体类

image-20200524221506223

配置

pom.xml

导入lombok纯粹是为了省一些写代码的操作,使用注解的方式来省下时间,但是初学者还是非常不建议使用这个

image-20200524232353430

导的spring是下面这个mvc的web架构的包,可以使用

image-20200524232418174

里面的包里面有这些分支,可以使用。

image-20200524232644861


<?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">

<!--这里的bean是一个对象
    id是变量名
    class是new的对象
    property相当于给对象中的属性配置一个值
    由spring创建的,原来是
    对象由spring注册管理等
-->
    <bean id="hello" class="com.yhy.pojo.Hello">
        <property name="str" value = "hello world"/>
    </bean>

    <!-- more bean definitions go here -->

</beans>

修改可以直接在xml文件中修改,其他的不用理了。所谓的IOC就是对象由spring创建、管理、装配。

核心

查看DeaultListableBeanFactory

image-20200524235137002

IOC(Inversion of Control)

The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container. --spinng官网上的一句华

直译过来就是这里两个包是spring框架中的IOC容器的基础,在上面的maven截图中,也是可以看到spring mvc里面有这两个包,要不然也不可能使用完整的spring框架。所以想学会这个IOC,这两个包的了解是必不可少的。

IOC创建对象

  • 默认是无参构造方法
  • 也可以有参构造(也是DI中的构造器注入)

环境

先总体的项目小测配置以及定义的各个类

image-20200526152135081

实体类

package com.yhy.pojo;

public class Hello {
    private String str;

    public Hello(String str) {
        this.str = str;
    }

    /**
     * @return String return the str
     */
    public String getStr() {
        return str;
    }

    /**
     * @param str the str to set
     */
    public void setStr(String str) {
        this.str = str;
    }

    public void show() {
        System.out.println(str);
    }

}

测试类

 @Test
    public void test()
    {
        //获得spring的上下文内容
        //拿到容器
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //使用容器获得对象
        Hello hello = (Hello) context.getBean("hello");
       
        hello.show();
    }

使用有参构造有几个方法

beans.xml中使用三种方式

  • 使用参数名
 <bean id="hello" class="com.yhy.pojo.Hello">
        <constructor-arg  name="str" value="yhy"/>
    </bean>
  • 使用下标索引
  <bean id="hello" class="com.yhy.pojo.Hello">
        <!-- 从零开始的索引值,多个参数的时候再使用别的参数 -->
        <constructor-arg index="0" value="hello world"/>
    </bean>

image-20200526151759464

  • 使用参数的类型来配置
  <bean id="hello" class="com.yhy.pojo.Hello">
        <constructor-arg type="java.lang.String" value="hello spring"/>
    </bean>

image-20200526152947985

其他

在.xml配置文件中还有两个选项。

image-20200526153337576

posted @ 2020-05-27 10:01  coderyhy  阅读(344)  评论(0编辑  收藏  举报