本篇內(nèi)容:
- 1、lookup方法注入
- 2粮揉、方法替換
一、lookup方法注入
- Spring的GGLib類包可以在運(yùn)行期動(dòng)態(tài)操作Class字節(jié)碼,使SpringIOC容器有復(fù)寫B(tài)ean的方法能力
1苗缩、創(chuàng)建java實(shí)體對(duì)象
public class CarObject {
?
private String title;
private String desc;
?
public void getData() {
System.out.println( "CarObject{" +
"title='" + title + '\'' +
", desc='" + desc + '\'' +
'}');
}
?
public String getTitle() {
return title;
}
?
public void setTitle(String title) {
this.title = title;
}
?
public String getDesc() {
return desc;
}
?
public void setDesc(String desc) {
this.desc = desc;
}
}
2、創(chuàng)建接口
public interface MagicBoss {
?
CarObject getCar();
?
}
3声诸、配置文件
<bean id="car" class="com.demo.CarObject" p:title="銀色" p:desc="雷克薩斯"/>
<bean id="magicBoss" class="com.demo.MagicBoss">
<lookup-method name="getCar" bean="car"/>
</bean>
說(shuō)明:
1酱讶、bean id="car" class="com.demo.CarObject" p:title="銀色" p:desc="雷克薩斯"
- car:propertype類型的Bean
- p:title="銀色":注入title屬性參數(shù)
2、lookup-method name="getCar" bean="car"
- lookup-method:為magicBoss提供動(dòng)態(tài)實(shí)現(xiàn)類返回bean="car"對(duì)象(每次都會(huì)從容器中獲取car實(shí)體對(duì)象)
注意:
- lookup方法注入是有一定范圍彼乌,一般在希望通過(guò)一個(gè)sigleton Bean獲取一個(gè)prototype Bean時(shí)使用
4泻肯、測(cè)試
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"file:src/main/resources/car.xml"})
public class CarObjectTest {
?
@Autowired
private MagicBoss magicBoss;
?
@Test
public void getBean() {
magicBoss.getCar().getData();
}
?
}
二渊迁、方法替換
- 使用某個(gè)bean的方法去替換另外一個(gè)Ben的方法
1、定義java類
public class CarFactory {
?
public CarObject getCar() {
CarObject carObject = new CarObject();
carObject.setDesc("寶馬3");
carObject.setTitle("灰色");
return carObject;
}
}
2灶挟、定義替換方法類
public class CarShop implements MethodReplacer {
public Object reimplement(Object o, Method method, Object[] objects) throws Throwable {
CarObject carObject = new CarObject();
carObject.setTitle("奔馳");
carObject.setDesc("黑色");
return carObject;
}
}
- 說(shuō)明:
- MethodReplacer接口中的方法用于替換目標(biāo)Bean的方法
3琉朽、配置文件
<!--方法替換-->
<bean id="carFactory" class="com.demo.CarFactory">
<replaced-method name="getCar" replacer="carSop"/>
</bean>
?
<bean id="carSop" class="com.demo.CarShop"/>
- 說(shuō)明:
- replaced-method name="getCar" replacer="carSop":使用carSop的MethodReplace接口方法替換本對(duì)象中的name="getCar"方法
4、測(cè)試
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"file:src/main/resources/car.xml"})
public class CarShopTest {
?
@Autowired
private CarFactory carFactory;
?
@Test
public void getCar(){
carFactory.getCar().getData();
}
}
- 說(shuō)明:
- 將會(huì)返回CarShop中的數(shù)據(jù)
demo代碼:
?
https://github.com/brusion/brusion-code/tree/master/demo-java/03%20-%20demo%20-%20spring/spring-study-4x/01-ioc/01-ioc-method