【Spring】学习笔记 01-HelloSpring

Spring开发相应的Maven依赖

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

这里我只导入了Spring-web依赖,因为该依赖会自动导入Spring开发的基础依赖

 

 

 POJO类

package com.wang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Hello {
    private String str;

}

 

Bean配置

<?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-->
    <bean id="hello" class="com.wang.pojo.Hello">
        <!-- collaborators and configuration for this bean go here -->
        <property name="str" value="SPRING"/>
    </bean>


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

</beans>

单元测试

@Test
    public void test01(){
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
/*
    类名 变量名=new 类型();
    Hello hello=new Hello();

    id=变量名
    class=new的对象
    property相当于给对象中的属性设置一个值!
* */
        Hello bean = context.getBean(Hello.class);
       //bean.setStr("Hello Spring!");
        System.out.println(bean.getStr());
    }

 

我们在测试代码中是通过ClassPathXmlApplicationContext类来获取bean对象的,接下来我们开下该类的继承关系

我们可以查看ApplicationContext接口的代码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.context;

import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.core.env.EnvironmentCapable;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.lang.Nullable;

public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
    @Nullable
    String getId();

    String getApplicationName();

    String getDisplayName();

    long getStartupDate();

    @Nullable
    ApplicationContext getParent();

    AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
}

 

posted @ 2022-06-04 21:37  王广元  阅读(18)  评论(0编辑  收藏  举报
分享到: