概要:(蓝色为本节所讲)
XML配置里的Bean自己主动装配
须要做的仅仅是在<bean>的autowire属性里指定自己主动装配的模式
代码实例具体解释:
文件夹结构:(仅仅用到com.coslay.beans.autowire)
Address.java
package com.coslay.beans.autowire;
public class Address {
private String city;
private String street;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
@Override
public String toString() {
return "Address [city=" + city + ", street=" + street + "]";
}
}
Car.java
package com.coslay.beans.autowire;
public class Car {
private String brand;
private double price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
}
package com.coslay.beans.autowire;
public class Person {
private String name;
private Address address;
private Car car;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Person [name=" + name + ", address=" + address + ", car=" + car
+ "]";
}
}
Main.java
package com.coslay.beans.autowire;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans-autowire.xml");
Person person = (Person) ctx.getBean("person");
System.out.println(person);
}
}
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.coslay.beans.autowire.Address" p:city="Beijing" p:street="HuiLongGuan"></bean>
<bean id="car" class="com.coslay.beans.autowire.Car" p:brand="Audi" p:price="30000"></bean>
<!-- <bean id="person" class="com.coslay.beans.autowire.Person" p:name="Tom" p:address-ref="address" p:car-ref="car"></bean> -->
<!--
能够使用autowire属性指定自己主动装配的方式
byName依据bean的名字和当前bean的setter风格的属性名进行自己主动装配,若有匹配的,则进行自己主动装配,若没有匹配的。则不装配
byType依据bean的类型和当前bean的属性的类型进行自己主动装配.若IOC容器中有一个以上的类型匹配的bean,则抛异常
-->
<bean id="person" class="com.coslay.beans.autowire.Person" p:name="Tom" autowire="byType"></bean>
</beans>
原文:https://www.cnblogs.com/ldxsuanfa/p/10886821.html