2017-10-16 51 views
-1

在服務實施中,在@Autowired的幫助下,我正在注入CollectInfo對象在serviceImpl中,但我得到NullPointerException@Autowired春季不工作集成

package net.group.cts.service.serviceImpl; 
     @Service 
     public class EmployeeImpl implements EmployeeService {  
      @Autowired 
      CollectInfo info; 

      public void processData(){ 
       info.getName(); 
      } 
     } 

package net.group.cts.model; 
    @Component 
    public class CollectInfo (){ 

     String name; 

     public String getName(){ 
      name = name + "Mr."; 
      return name;} 
     } 

    } 

Xmlconfig.xml

<context:annotation-config/> 
<context:component-scan base-package="net.group.cts"/> 
<bean id="info" class="net.group.emp.model.CollectInfo "/> 
+0

如果您使用@Component註釋了類,那麼您可以共享CollectInfo class.check嗎 –

+0

是否'EmployeeImpl'彈簧容器被管理? –

+0

@Vikram是我定義了 – Doss

回答

1

如果該類不是一個Spring bean你不能在一個類中注入一個bean。
EmployeeImpl未註明任何Spring bean stereotype,例如@Component@Service

加入其中的一個對EmployeeImpl並確保兩個類都位於由Spring <context:component-scan base-package="net.group.emp.service"/> 掃描包裏面,它應該沒問題。

此外,這兩個註釋一個bean與@Component:

@Component 
public class CollectInfo (){...} 

,並在Spring XML配置配置它:

<bean id="info" class="net.group.emp.model.CollectInfo "/> 

是多餘的。
它最終會創建兩個bean:一個名稱爲collectInfo,另一個名爲info

我建議你贊成通過xml配置註釋,因爲它是可能的(這是大多數情況下)。

+0

我不能從xml中刪除這個 bcoz我正在使用它來工作正常的網關目的。 – Doss

+0

但仍面臨相同的空指針異常 – Doss