spring5之关于ioc的一些基本操作
讲之说的ioc和aop补上
spring中两大核心ioc和aop,ioc定义叫:控制反转。但根据我学下来,根据尚硅谷的讲解,我理解的是将对象交给spring进行管理,对象创建,属性注入等等,目的是解耦,方便管理,简化代码,它是基于工厂模式实现的,理解不到为还请多多包涵。
接下来进行一些简单的ioc的操作,它有注解和xml两种实现方式,首先根据xml配置文件来操作
首先是几个实体类

public class Book { private String bname; private String address; public void setAddress(String address) { this.address = address; } //set方法注入 public void setBname(String bname) { this.bname = bname; } public void shuchu(){ System.out.println(bname); } public void shuchu1(){ System.out.println(bname+","+address); } } public class Order { private String oname; private String address; public Order(String oname, String address) { this.oname = oname; this.address = address; } public void test(){ System.out.println(oname+","+address); } } public class User { private String username; public void add() { System.out.println("asdqw"); } }
然后是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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 对象注入--> <bean id="user" class="Spring5_test_class.User"> </bean> <!-- set方法注入属性--> <bean id="book" class="Spring5_test_class.Book"> <!-- 使用property完成属性的注入--> <property name="bname" value="红楼梦"></property> <!-- 设置固定值null--> <!-- <property name="address">--> <!-- <null></null>--> <!-- </property>--> <!-- 设置属性值中包含特殊符号,把特殊符号内容写到CDATA--> <property name="address"> <value> <![CDATA[<<北京>>]]> </value> </property> </bean> <!-- 有参数构造注入属性--> <bean id="orders" class="Spring5_test_class.Order"> <constructor-arg name="oname" value="abc"></constructor-arg> <constructor-arg name="address" value="中国"></constructor-arg> </bean> </beans>
测试:

public class TestSpring5 { @Test public void testadd() { ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); //获取配置的创建对象 User user1 = context.getBean("user", User.class); user1.add(); System.out.println(user1); } @Test public void testbook(){ ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml"); //获取配置的创建对象 Book book= context.getBean("book", Book.class); book.shuchu1(); } @Test public void testorder(){ ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml"); //获取配置的创建对象 Order order= context.getBean("orders", Order.class); order.test(); } }
今天这只是一个简单属性注入,之后在补上外部bean注入,级联赋值等等
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?