文章目录
1.byType
在spring-contex.xml文件中
<!-- primary="true" 需要指定主要的注入对象,不然报错 -->
<bean id="ssdDisk" class="org.example.service.impl.SSDDisk" primary="true"></bean>
<bean id="computer" class="org.example.service.Computer" autowire="byType"></bean>
1-2.pojo类
public class Computer {
private IDisk ssdDisk;
}
1-3.test类
Computer computer = context.getBean(Computer.class);
computer.print("图片");
2.byName
2-1.在spring-contex.xml文件中
<bean id="computer" class="org.example.service.Computer" autowire="byName"></bean>
2-2.在pojo的实体类中
可以根据ssdDisk自动注入
public class Computer {
private IDisk ssdDisk;
private String brand;
public Computer() {
}
public Computer(IDisk ssdDisk, String brand) {
this.ssdDisk = ssdDisk;
this.brand = brand;
}
public IDisk getSsdDisk() {
return ssdDisk;
}
public void setSsdDisk(IDisk ssdDisk) {
this.ssdDisk = ssdDisk;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public void print(String value) {
ssdDisk.output(this.brand + "#" + value);
}
}
2-3 test类中 测试
Computer computer = context.getBean(Computer.class);
computer.print("图片");
3.Scope 设置 单例使用,多例使用
<!-- 可以scope来控制是否为单例或者多例;在实际的工作中都是单例 -->
<!-- <bean id="student" class="org.example.pojo.Student" scope="singleton"></bean>-->
<bean id="student" class="org.example.pojo.Student" scope="prototype"></bean>