ref:https://www.tutorialspoint.com/spring/spring_autowiring_byname.htm
project:Working Set: Spring>Project:Spring02>的
entity>Person/User 和ApplicationContext2.xml以及test>Test2
没有使用注释的时候,需要在spring的xml配置文件中手动配置并关联bean.
获取bean需要使用ClassPathXmlApplicationContext类继承自AbstractApplicationContext类中的getBean("bean name")方法.
有时候,为了避免歧义,还要写带有classpath:的完整路径.
bean对应的类中,只需要设置和<bean><property name="propertiesName">中对应的set方法,格式如下:
setPropertiesName(...)
不需要无参和全参构造函数和get方法.
,需要在property中添加对应的属性.
其中如果没有使用别名,需要property中的name attribute和类中的属性名保持一致.
*还可以通过bean中的autowire attribute来和属性 建立关系.
byName是通过参数名来在配置文件中寻找 和 "所需要的参数" 对应名称的bean,也就是和setPropertiesName()中的PropertiesName同名的bean.
比如:
PC有个CPU cpu属性,以及其他如String videoCard, Integer price;
那么<bean name="PC"如果设置 autowire="byType">
<property name="videoCard" value="GTX 1080">
<property name="price" value="20000">
</bean>
虽然没有配置Cpu类型的cpu属性.
但是如果配置文件中有个
<bean id="cpu" class=".....CPU"
就会寻找配置文件中的该bean.
因为类型是CPU.
*如果autowire是"byName"
就会寻找到和PC中的属性[CPU cpu]中的set方法的名称
因为setCpu和cpu对应.
为了不混淆.
将PC中的CPU属性名设置成 cpu_ClassProp
将其set方法设置成setCpu_Set()
set方法的形参是cpu_Param
将bean的id设置成cpu_Bean
然后,byName对比的是
cpu_Bean和cpu_Set()是否相等.
如果找到setXYZ()和id为xYZ的bean,则会匹配.
将其作为属性注入到PC中,
等效于
<property name="cpu_Set" ref="cpu_Bean >