Spring基础02
Spring基础02
Hello Spring
-
IDEA 新建maven项目, pom.xml导入相关依赖。
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.8.RELEASE</version> </dependency>
-
编写相关代码:
-
编写一个Hello实体类:
package com.test.pojo.Hello; public class Hello { public Hello(String str){ this.str = str; } private String str; public String getStr() { return str; } public void setStr(String str) { this.str = str; } public void show(String str) { System.out.println("Hello " + str); } @Override public String toString() { return "Hello{" + "str='" + str + '\'' + '}'; } }
-
编写配置文件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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 使用Spring来创建对象,在Spring这些都被称为Bean 类型 变量名 = new 类型 Hello hello = new Hello(); id = 变量名 calss = new 的对象 property 相当于给对象的一个属性赋值 --> <bean id="hello" class="com.test.pojo.Hello"> <property name="str" value="hello spring"></property> </bean> </beans>
-
编写test文件:
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { // 获取Spring容器的上下文对象!执行完这句,beans.xml中定义的所有的bean都实例化完成了 ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); // 我们的对象现在都在Spring容器中管理了,我们要使用就从里面取出来就行。 Hello hello = (Hello)context.getBean("hello"); System.out.println(hello); // 输出Hello{str='hello spring'} } }
-
-
IoC创建对象的方式:
-
使用无参构造方法创建。
-
实体类中有有参构造方法,使用有参构造方法创建。
-
下标方式
<!-- 有参构造 下标方式--> <bean id="hello" class="Hello"> <constructor-arg index="0" value="hello"/> </bean>
-
type方式 (类型重复,不推荐)
<!-- 有参构造 type方式--> <bean id="hello" class="Hello"> <constructor-arg type="java.lang.String" value="hello"/> </bean>
-
直接通过参数名
<!-- 有参构造 通过参数名--> <bean id="hello" class="Hello"> <!-- 如果参数是对象,就使用ref --> <constructor-arg name="str" value="hello"/> </bean>
-
-
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY