Peroe 实体类:
package com.cn;
public class Peroe {
private String name;
private Dog dog;//引用类型
private Cat cat;//引用类型
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
@Override
public String toString() {
return "Peroe{" +
"name='" + name + '\'' +
", dog=" + dog +
", cat=" + cat +
'}';
}
}
Dog 实体类:
package com.cn;
public class Dog {
/**
作者
时间
类的描述
***/
public void dog(){
System.out.println("wangwang");
}
}
Cat 实体类:
package com.cn;
public class Cat {
/**
作者
时间
类的描述
***/
public void show(){
System.out.println("mianian");
}
}
bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="cat" class="com.cn.Cat"/>
<bean id="dog" class="com.cn.Dog"/>
<bean id="per" class="com.cn.Peroe">
<property name="name" value="java"/>
<!--ref:引入Bean-->
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
</beans>
测试类:
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");//实例化容器
Peroe per = (Peroe)context.getBean("per");
System.out.println(per.getName());
per.getDog().dog();
per.getCat().show();
}
自动装配优化bean.xml
设置autowire=“byNme/byType”
1、ByName:启动在容器上下中查找自己set后面的beanid
bean id="cat" class="com.cn.Cat"/>
<bean id="dog" class="com.cn.Dog"/>
<bean id="per" class="com.cn.Peroe" autowire="byName">
</bean>
2、byType:如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配;如果存在多个该类型bean,那么抛出异常,并指出不能使用byType方式进行自动装配;如果没有找到相匹配的bean,则什么事都不发生
bean id="cat" class="com.cn.Cat"/>
<bean id="dog" class="com.cn.Dog"/>
<bean id="per" class="com.cn.Peroe" autowire="byType">
</bean>
spring中Byname和Bytype区别:
byName:根据属性名自动装配。此选项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配。
byType:如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配;如果存在多个该类型bean,那么抛出异常,并指出不能使用byType方式进行自动装配;如果没有找到相匹配的bean,则什么事都不发生,也可以通过设置