2015-04-01 62 views
1

我试图Autowire一个bean的实现,但它返回一个空指针异常。春季4 @Autowire没有正确绑定?

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 i = 1; i <=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); 
    } 
} 

在我的applicationContext.xml我已经添加了以下

<bean id="multiply" class="org.com.core.MultiplyImpA" scope="prototype"/> 

现在在运行时,我收到了NullPointerExpection。乘以零。

用于测试目的我试过这个。它的工作原理,我明白在这里我明确地获得Bean。所以这意味着autowire不起作用?有什么我失踪?

Multiply m = (Multiply)factory.getBean("multiply"); 
System.out.println(m.multiplier(2,4); 
+0

发布您的spring.xml。 – 2015-04-01 03:07:12

+0

是的,请spring.xml。你如何实例化'Calculator'? – fateddy 2015-04-01 04:55:07

+0

现在我正在从junit测试用例中调用。 – user1364861 2015-04-01 05:18:42

回答

0

似乎你在你的bean xml中有一个错字。

而不是

<bean id="multiply" class="package org.com.core.MultiplyImpA" scope="prototype"/> 

应该(使用完全合格的类名只)

<bean id="multiply" class="org.com.core.MultiplyImpA" scope="prototype"/> 

编辑:

可能出现的错误可能是因为Calculator类没有管理春天。实例化使用new运营商因为没有办法,春天会得到一个引用注入合作者将会失败等级:

Calculator calculator = new Calculator(); 
calculator.calcMultiply(1, 2); // would throw a NPE because the `Multiply` instance (in your case `MultiplyImpA`) has not been injected. 

所以不是实例化Calculator类使用的弹簧:

<bean id="calculator" class="org.com.service.Calculator"/> 
<bean id="multiply" class="org.com.core.MultiplyImpA"/> 

检索通过应用程序上下文:

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application-context.xml"); 
Calculator calculator = ctx.getBean(Calculator.class); 

然后Spring会通过扫描来管理依赖关系注释,查看字段类型并尝试从应用程序上下文中查找合格的bean。

+0

错字只在这里不在我的实际程序中。感谢您指出。 – user1364861 2015-04-01 04:47:53

+0

它没有工作。 ApplocationContext抱怨它有两种类型的实现,然后我从applicationContext中移除了implements bean,认为它可以工作,但它不会工作。 – user1364861 2015-04-01 15:15:25

+0

然后请发布您的完整应用程序上下文xml和引导应用程序的单元测试/或代码片段。否则,将很难提供帮助。 – fateddy 2015-04-01 16:27:17

1

根据类型自动装配解析,因为有两个不同的impl,所以需要使用限定符来缩小它。所以试试下面。

public Calculator { 
@Autowire 
@Qualifier("multiply") 
private Multiply multiply ; 
public int calcMultiply(int a, int b){ 
    return multiply.multipler(a,b); 
} 
} 
+0

我已经试过了。它没有帮助。我不明白为什么乘法仍为空? – user1364861 2015-04-01 04:26:45