【Spring】学习笔记03-IOC创建对象
POJO
@Data @AllArgsConstructor @NoArgsConstructor public class User { private String name; }
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--> <bean id="user" class="com.wang.pojo.User"> <!-- collaborators and configuration for this bean go here --> <property name="name" value="SPRING"/> </bean> <!-- more bean definitions go here --> </beans>
单元测试
@Test public void test01(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); User user = (User)context.getBean("user"); System.out.println(user.getName()); }
默认情况下,IOC通过实体类的无参构造创建对象,然后通过set方法注入属性
还可以使用构造器注入,此时我们去掉实体类的无参构造器
@Data @AllArgsConstructor public class User { private String name; }
方法1:下标赋值
beans.xml
bean id="user1" class="com.wang.pojo.User"> <constructor-arg index="0" value="Spring_construct_index"/> </bean>
单元测试
@Test public void test02(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); User user = (User) context.getBean("user1"); System.out.println(user.getName()); }
//测试结果
//Spring_construct_index
//进程已结束,退出代码为 0
方法二:根据参数类型赋值
beans.xml
<bean id="user2" class="com.wang.pojo.User"> <constructor-arg type="java.lang.String" value="Spring_contruct_type"/> </bean>
单元测试
@Test public void test03(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); User user = (User) context.getBean("user2"); System.out.println(user.getName()); }
//Spring_contruct_type
//进程已结束,退出代码为 0
当前该方法是不建议使用的,在实体类含有多个相同类型的参数时。
方法三:直接通过参数创建对象
beans.xml
<bean id="user3" class="com.wang.pojo.User"> <constructor-arg name="name" value="Spring_contruct_name"/> </bean>
单元测试:
@Test public void test04(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); User user = (User) context.getBean("user3"); System.out.println(user.getName()); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现