通过set方式注入
bean的定义:
package com.ydoing.demo;
public class Person {
private Computer computer;
public void setComputer(Computer computer) {
this.computer = computer;
}
public void useComputer() {
computer.start();
}
}
bean的配置:
<bean id="person" class="com.ydoing.demo.Person">
<property name="computer" ref="computer" />
</bean>
通过构造器注入
注入基本类型
bean的定义:
package com.ydoing.demo;
public class CPU {
private String name;
public CPU(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
bean的配置:
<bean id="cpu" class="com.ydoing.demo.CPU">
<constructor-arg value="Intel"/>
</bean>
注入对象引用
package com.ydoing.demo;
public class Computer {
private String name;
private CPU cpu;
public Computer(String name, CPU cpu) {
this.name = name;
this.cpu = cpu;
}
public void start() {
System.out.println(name + "computer run");
System.out.println("CPU name is: " + cpu.getName());
}
}
bean的配置
<bean id="computer" class="com.ydoing.demo.Computer">
<constructor-arg value="Del"/>
<constructor-arg ref="cpu"/>
</bean>
通过工厂方法
适合私有构造器以及没有set方法的bean。
package com.ydoing.demo;
public class Singleton {
private Singleton() {
}
private static class SingletonHolder {
static final Singleton instance = new Singleton();
}
public static final Singleton getInstance() {
return SingletonHolder.instance;
}
}
bean的配置
<bean id="singleton" class="com.ydoing.demo.Singleton" factory-method="getInstance"/>
装配集合
list
<property name="memorys">
<list>
<ref bean="Kingston" />
<ref bean="Apacer" />
</list>
</property>
或者
<property name="memorys">
<list>
<value>1</value>
<value>2</value>
</list>
</property>
set
<property name="memorys">
<set>
<ref bean="Kingston" />
<ref bean="Apacer" />
</set>
</property>
map
<property name="memorys">
<map>
<entry key="key1" value="11"/>
<entry key="key2" value="22"/>
</map>
</property>
或者
<property name="memorys">
<map>
<entry key-ref="key1" value-ref="bean1"/>
<entry key-ref="key2" value-ref="bean2"/>
</map>
</property>
props
props的key和value必须是String类型。
<property name="memorys">
<props>
<key>OK</key>
<key>No</key>
</props>
</property>
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-29 19:09:49