DiByType.java
package com.javacode2018.lesson001.demo6;
/**
* 按照类型自动注入
*/
public class DiAutowireByType {
public static class Service1 {
private String desc;
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "Service1{" +
"desc='" + desc + '\'' +
'}';
}
}
public static class Service2 {
private String desc;
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "Service2{" +
"desc='" + desc + '\'' +
'}';
}
}
private Service1 service1;
private Service2 service2;
public Service1 getService1() {
return service1;
}
public void setService1(Service1 service1) {
System.out.println("setService1->" + service1); //@1
this.service1 = service1;
}
public Service2 getService2() {
return service2;
}
public void setService2(Service2 service2) {
System.out.println("setService2->" + service2); //@2
this.service2 = service2;
}
@Override
public String toString() {
return "DiByType{" +
"service1=" + service1 +
", service2=" + service2 +
'}';
}
}
DiAutowireByType类中有2个set方法分别来注入Service1和Service2,两个set方法中都输出了一行文字,一会执行的时候可以通过这个输出可以看出set方法是否被调用了。
diAutowireByName.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="service1" class="com.javacode2018.lesson001.demo6.DiAutowireByName$Service1">
<property name="desc" value="service1"/>
</bean>
<bean id="service2" class="com.javacode2018.lesson001.demo6.DiAutowireByName$Service2">
<property name="desc" value="service2"/>
</bean>
<bean id="service2-1" class="com.javacode2018.lesson001.demo6.DiAutowireByName$Service2">
<property name="desc" value="service2-1"/>
</bean>
<!-- autowire:byName 配置按照name进行自动注入 -->
<bean id="diAutowireByName1" class="com.javacode2018.lesson001.demo6.DiAutowireByName" autowire="byName"/>
<!-- 当配置了自动注入,还可以使用手动的方式自动注入进行覆盖,手动的优先级更高一些 -->
<bean id="diAutowireByName2" class="com.javacode2018.lesson001.demo6.DiAutowireByName" autowire="byName">
<property name="service2" ref="service2-1"/>
</bean