java - Spring 4 @Autowire not binding correctly? -
i m trying autowire bean implementation returns null pointer exception.
package org.com.api; public interface multiply { public int multipler(int a, int b); } package org.com.core; import org.com.api.multiply; public class multiplyimpa implements multiply { public int multipler(int a, int b){ return a*b; } } package org.com.core; import org.com.api.multiply; public class multiplyimpb implements multiply { public int multipler(int a, int b){ int total = 0; for(int = 1; <=b; i++){ total += a; } return total; } } package org.com.service; import org.com.api.multiply; public calculator { @autowire private multiply multiply; public int calcmultiply(int a, int b){ return multiply.multipler(a,b); } }
in applicationcontext.xml have added following
<bean id="multiply" class="org.com.core.multiplyimpa" scope="prototype"/>
now in runtime nullpointerexpection. multiply null.
for testing purpose tried this. works, understand here m explicitly getting bean. means autowire didnt work ? there m missing ?
multiply m = (multiply)factory.getbean("multiply"); system.out.println(m.multiplier(2,4);
seems have typo in bean xml.
instead of
<bean id="multiply" class="package org.com.core.multiplyimpa" scope="prototype"/>
it should (using full qualified classname only)
<bean id="multiply" class="org.com.core.multiplyimpa" scope="prototype"/>
edit:
possible error calculator
class not managed spring. instantiating class using new
operator fail because there no way spring reference inject collaborator:
calculator calculator = new calculator(); calculator.calcmultiply(1, 2); // throw npe because `multiply` instance (in case `multiplyimpa`) has not been injected.
so instead instantiate calculator
class using spring:
<bean id="calculator" class="org.com.service.calculator"/> <bean id="multiply" class="org.com.core.multiplyimpa"/>
retrieve through application-context:
classpathxmlapplicationcontext ctx = new classpathxmlapplicationcontext("application-context.xml"); calculator calculator = ctx.getbean(calculator.class);
spring manage dependencies scanning @autowired
annotation, looking @ field type , trying find qualified bean application context.
Comments
Post a Comment