Spring对IOC的实现,依赖注入之c命名空间注入
1.开闭原则,依赖倒置原则及IOC控制反转
2.Spring对IOC的实现,依赖注入之c命名空间注入
3.Spring对IOC的实现,依赖注入之p命名空间注入4.GoF之工厂模式5.BeanFactory和FactoryBean的区别学习spring要点之IOC控制反转的实现依赖注入
还是先入门,简单实现下c命名空间注入
c命名空间是简化构造方法注入的
先简单说明下什么是c命名空间的两个前提
1、需要在xml配置文件头部添加信息:
xmlns:c="http://www.springframework.org/schema/c"
2、需要提供构造方法
简单实现下
首先pom依赖是spring context依赖,junit依赖
<dependencies>
<!-- spring context依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.0-M2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
接下来就是给一个java类(我这个案例pojo类是在com.spring6.bean)包下的
注意是需要提供构造方法的
public class People {
private String name;
private int age;
private boolean sex;
// c命名空间是简化构造注入的。
// c命名空间注入办法是基于构造方法的。
public People(String name, int age, boolean sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
'}';
}
}
然后我们在spring.xml配置文件下进行配置(配置文件在根路径也就是resources目录下)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
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">
<!-- 第一步:在spring配置文件头部添加:xmlns:c="http://www.springframework.org/schema/c"-->
<!-- 第二步:使用c:_0 下标方法 或者 c:name 参数名方式-->
<bean id="peopleBean" class="com.spring6.bean.People" c:_0="zhangsan" c:_1="30" c:_2="true"></bean>
</beans>
测试类
@Test
public void testC() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-c.xml");
People peopleBean = applicationContext.getBean("peopleBean",People.class);
System.out.println(peopleBean);
}
测试结果
我们也是成功的给属性赋值了
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具