【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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现