方法注入需要依赖CGLib包,CGLib可以在运行期间动态操作Class字节码,为bean动态创建子类或者实现类,配置文件通过lookup-method标签,告诉spring 需要注入方法的名称,和返回的bean对象,只要将返回的bean对象属性设置成prototype类型即可!
应用场景:在一个singleton bean 中获取一个prototype bean
举例:
Iphone7.java
package com.yaspeed.spring.bean.lookup;
public class Iphone7{
private String name;
private int price;
private int contain;
public Iphone7(){
System.out.println("调用构造函数Iphone7()...");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getContain() {
return contain;
}
public void setContain(int contain) {
this.contain = contain;
}
@Override
public String toString() {
return "Iphone7 [name=" + name + ", price=" + price + ", contain=" + contain + "]";
}
}
MagicIphone.java
此处定义成接口或者抽象类都可以
package com.yaspeed.spring.bean.lookup;
public interface MagicIphone {
Iphone7 getIphone();
}
bean-lookup.xml
主要通过looup-method标签实现
<?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="iphone7" class="com.yaspeed.spring.bean.lookup.Iphone7" scope="prototype"
p:name="iphone7" p:price="7188" p:contain="128">
</bean>
<bean id="magicIphone" class="com.yaspeed.spring.bean.lookup.MagicIphone" scope="singleton">
<lookup-method name="getIphone" bean="iphone7"/>
</bean>
</beans>
测试方法:
package com.yaspeed.spring.bean.lookup;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("bean-lookup.xml");
MagicIphone magicIphone =(MagicIphone)ctx.getBean("magicIphone");
if(magicIphone.getIphone()!=magicIphone.getIphone()){
System.out.println("每次取得的对象不同!!");
}
}
}
结果:
调用构造函数Iphone7()...
调用构造函数Iphone7()...
每次取得的对象不同!!