Spring中装配bean
一、自动装配bean
<bean id = "master" class="Master" autowire="byType">
其中autowire的取值有:no,byType,byName,constructor,autodetect,default
注意事项:
默认是no,意思是不自动装配(注意跟default的区别)
byType :寻找和属性类型相同的bean,如果找不到,则装配不上,如果找到多个,则会抛出异常
byName:寻找和属性名相同的bean,若找不到则装配不上
constructor:查找和bean的构造参数一致的或者多个bean,若找不到或者找到多个,则抛出异常
autodetect :按照constructor 或者byType 的去选择(constructor优先级高)
default:这个需要在<beans default-autowire="指定">,注意此处不是<bean>是<beans >中指定,意思是给所有的bean设置装配方式
二、启动注解装配
在<beans >标签中,有<context:annotation-config />这个标签,当在配置文件中有这个标签后,在相应的java文件中就可以使用注解装配bean了
三、在spring中如何调用配置的属性文件(xx.properties)
当某些<bean>需要去调用属性文件的时候,就需要在bean中配置属性文件了:
在<beans >标签中,配置如下:
<context:property-placeholder location="属性文件的地址"> //如果有多个属性文件,需要使用“,”隔开
调用的话,直接在<bean>中调用就行 比如:
<bean id = "dbutil" class="xxxxxxx">
<property name = "name" value="${name}"> //其中的$是占位符,$中的name代表是属性文件中的的name
<property name = "driver" value="${driver}">
</bean>
还有一种方法是,直接在bean中配置:
<bean class="xxxxxxxxxxPropertyPlaceholderConfigurer">
<property name = "locations">
<list>
<value>xxxxxx.properties</value> //属性文件的详细路径
<value>xxxxxx2.properties</value>
</list>
</property>
</bean>