用于方法注入的Spring lookup-method属性,有助于在每次调用该方法时创建新实例。容器也动态地为该类创建子类并覆盖该方法。但是,对我来说,只为正常注射和方法注射创建了一个实例。我已经发布了我尝试过的完整代码。我想完全理解查找方法如何工作以及它与正常注入的不同之处。
<bean id="processor" class="org.RequestProcessor">
<lookup-method name="getResourceA" bean="resourceA"/>
</bean>
<bean id="resourceA" class="org.ResourceA"/>
<bean id="resourceB" class="org.ResourceB"/>
public abstract class RequestProcessor {
@Autowired
ResourceB resourceB;
public ResourceB getResourceB(){
return resourceB;
}
abstract ResourceA getResourceA();
}
public class ResourceA {
String url ="http://localhost:8080";
public ResourceA(){
System.out.println("Resource A instance creation");
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
public class ResourceB {
String url ="http://localhost:8081";
public ResourceB(){
System.out.println("Resource B instance creation");
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
public class SpringExample {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("org/applicationContext.xml");
RequestProcessor processor = (RequestProcessor)applicationContext.getBean("processor");
for (int i=0;i<3;i++){
ResourceA resource = processor.getResourceA();
System.out.println(resource.getUrl());
}
for (int i=0;i<3;i++){
ResourceB resource = processor.getResourceB();
System.out.println(resource.getUrl());
}
}
}
上述程序的输出是:
Resource B instance creation
Resource A instance creation
http://localhost:8080
http://localhost:8080
http://localhost:8080
http://localhost:8081
http://localhost:8081
http://localhost:8081
答案 0 :(得分:1)
我找到了问题的答案。我在两个bean中遗漏了scope属性。我必须将scope =“prototype”添加到两个bean中,如:
<bean id="resourceA" class="org.ResourceA" scope="prototype"/>
<bean id="resourceB" class="org.ResourceB" scope="prototype"/>
现在更改后输出为:
Resource B instance creation
Resource A instance creation
http://localhost:8080
Resource A instance creation
http://localhost:8080
Resource A instance creation
http://localhost:8080
http://localhost:8081
http://localhost:8081
http://localhost:8081