spring依赖注入简介以及依赖注入的两种方式
1、spring依赖注入简介
依赖注入:Set注入
1.依赖:bean对象创建依赖于容器!
2.注入:bean对象中的所有属性,由容器来注入!
2、依赖注入的两种方式
实体类:
package com.tang.pojo;
public class People {
private String name;
private Cat cat;
private Dog dog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", cat=" + cat +
", dog=" + dog +
'}';
}
}
给People进行依赖注入。(自动装配)(Cat和Dog是实体类):
1、byName:会自动在容器上下文中查找,和自己对象Set方法后面的值对应的 beanid!
<bean id="dog" class="com.tang.pojo.Dog"></bean>
<bean id="cat" class="com.tang.pojo.Cat"></bean>
<bean id="people" class="com.tang.pojo.People" autowire="byName">
<property name="name" value="唐世华"></property>
</bean>
People的Dog和bean中的dog对应,cat也一样
2、byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean!
<bean id="dog" class="com.tang.pojo.Dog"></bean>
<bean id="cat1" class="com.tang.pojo.Cat"></bean>
<bean id="people" class="com.tang.pojo.People" autowire="byType">
<property name="name" value="唐世华"></property>
</bean>
People中的Dog和Cat和bean中的cat和dog中的class对应!
3、总结
小结:
1.byName的时候,需要保证所有bean的id唯一,
并且这个bean需要和自动注入的属性的set方法的值一致!
2.byType的时候,需要保证所有bean的iclass唯一,
并且这个bean需要和自动注入的属性的类型一致!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)