spring–基础–03–依赖注入(DI)
代码地址
https://gitee.com/DanShenGuiZu/learnDemo.git
1、介绍
管理Bean之间的依赖关系,比如说A类中含有B类。
2、依赖注入方式
- 基于带参构造函数的依赖注入
- 基于setter方法的依赖注入,调用bean的setter方法来实现的。
3、案例
3.1、基于带参构造函数的依赖注入
输出:
..... Creating shared instance of singleton bean 'hello8_1'
Hello8--->helloword
3.2、基于setter方法的依赖注入
3.3、内部Beans
bean的范围内定义的bean
3.4、注入集合
- list:注入一列值
- set:注入一列值
- map:注入键值对(k-v)的集合,k,v可以是任何类型。
- props:注入键值对(k-v)的集合,k,v都是字符串类型。
配置和代码
<bean id="hello11" class="com.example.demolearn.other.spring.demo1.Hello11">
<property name="list1">
<list>
<value>1</value>
<value>2</value>
<!--注入对象引用-->
<ref bean="hello9"/>
<!--注入 null和空字符串的值-->
<value>""</value>
</list>
</property>
<property name="set1">
<list>
<value>3</value>
<value>4</value>
<ref bean="hello9"/>
</list>
</property>
<property name="map">
<map>
<entry key="1" value="f1"/>
<entry key="2" value="f2"/>
<entry key="3" value-ref="hello9"/>
</map>
</property>
<property name="props">
<props>
<prop key="01">one</prop>
<prop key="02">two</prop>
</props>
</property>
</bean>
@Data
public class Hello11 {
private List list1;
private Set set1;
private Map map;
private Properties props;
public static void main(String[] args){
String pathHello = "./other\\Bean.xml";
AbstractApplicationContext context = new ClassPathXmlApplicationContext(pathHello);
Hello11 hello11 =(Hello11)context.getBean("hello11");
System.out.println("----------list-------");
for(Object o : hello11.getList1()){
System.out.println(o.toString());
}
System.out.println("----------set1-------");
for(Object o : hello11.getSet1()){
System.out.println(o.toString());
}
System.out.println("----------map-------");
for(Object key : hello11.getMap().entrySet()){
System.out.println(key.toString());
}
System.out.println("----------props-------");
for(Object key : hello11.getProps().entrySet()){
System.out.println(key.toString());
}
}
}
输出
----------
----------list-------
1
2
com.example.demolearn.other.spring.demo1.Hello9@77846d2c
""
----------set1-------
3
4
com.example.demolearn.other.spring.demo1.Hello9@77846d2c
----------map-------
1=f1
2=f2
3=com.example.demolearn.other.spring.demo1.Hello9@77846d2c
----------props-------
02=two
01=one