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 getNam
·
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需要和自动注入的属性的类型一致!
更多推荐
已为社区贡献2条内容
所有评论(0)