HelloSpring

HelloSpring(第一个Spring程序)

1、环境搭建

需要导入相应的依赖

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.22</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

2、具体操作

1、创建hello类

public class Hello {
    private String s;

    public Hello() {
    }

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

    public String getS() {
        return s;
    }

    public void setS(String s) {
        this.s = s;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "s='" + s + '\'' +
                '}';
    }
}

2、配置xml文件(ApplicationContext.xml)

这里的配置文件可以去spring官方文档进行查询

核心技术 (springdoc.cn)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lbtzibkM-1682257008175)(D:\笔记\框架\Spring框架\HelloSpring.assets\image-20230422103937488.png)]

3、使用spring来创建对象

在spring中其所创建的对象都称之为Bean。

3.1bean标签

在使用spring创建对象前我们先学习以下bean标签

其基本语法为:

<bean id="xxx" class="xxx.xxx.xxx.xxx.xxx">
    <property name="x" value="xxxxx"/>
</bean>

其中bean代表这是一个bean,其中:

  • id属性是bean的标识
  • class是这个bean指向的一个类即需要new的对象
  • property代表属性
    • name代表属性的名称
    • value代表的是属性值

下面我们使用Spring来创建hello类,并且为他的属性赋值为“hello,spring”

<bean id="hello" class="com.fan.hello.pojo.Hello">
    <property name="s" value="hello,spring"/>
</bean>

这样我们就相当于把hello类托管给了spring

那么我们该如何使用spring来进行创建呢?

3.2实例化一个容器

Spring中提供了一个ApplicationContext构造函数的一条或多条路径是资源字符串,它让容器从各种外部资源加载配置元数据。

ApplicationContext context = new ClassPathXmlApplicationContext("xxx.xml","xxx.xml");

并且可以使用getBean(String name,Class requiredType)来检索Bean的实例。

下面我们来实例化容器并且来使用容器获取相应的bean。

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Hello hello = context.getBean("hello", Hello.class);
    System.out.println(hello);
}

这样我们通过spring来获取到了hello的实例,我们可以发现整个过程中我们并没有使用关键字new对hello类进行实例化,spring帮我们做了这些事情。

思考:

  • hello对象是由谁来创建的?

    hello是由Spring帮我们创建的。

  • hello的属性是如何设置的?

    属性是Spring容器进行设置的

那么这个过程就叫做IOC控制反转

要注意的是,依赖注入是通过set方法来实现的。怎么理解呢?

就是在Spring中对Bean的属性值注入时是通过Set方法来实现的,如果class类中没有set方法则不能实现属性的注入。

是Spring容器进行设置的

那么这个过程就叫做IOC控制反转

要注意的是,依赖注入是通过set方法来实现的。怎么理解呢?

就是在Spring中对Bean的属性值注入时是通过Set方法来实现的,如果class类中没有set方法则不能实现属性的注入。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值