Spring lookup-method instance creation -
spring lookup-method attribute used method injection helps creates fresh instances every time when method invoked. container dynamically creates subclass class , overrides method. but, me 1 instances created normal injection , method injection. have posted complete code have tried. want understand how lookup-method working , how different normal injection.
<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 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"); (int i=0;i<3;i++){ resourcea resource = processor.getresourcea(); system.out.println(resource.geturl()); } (int i=0;i<3;i++){ resourceb resource = processor.getresourceb(); system.out.println(resource.geturl()); } } }
output above program is:
resource b instance creation resource instance creation http://localhost:8080 http://localhost:8080 http://localhost:8080 http://localhost:8081 http://localhost:8081 http://localhost:8081
i have found answer problem. have missed scope attribute in 2 beans. have add scope="prototype" 2 beans like:
<bean id="resourcea" class="org.resourcea" scope="prototype"/> <bean id="resourceb" class="org.resourceb" scope="prototype"/>
after change output is:
resource b instance creation resource instance creation http://localhost:8080 resource instance creation http://localhost:8080 resource instance creation http://localhost:8080 http://localhost:8081 http://localhost:8081 http://localhost:8081
Comments
Post a Comment