2016-04-06 26 views
0

我有這樣的服務類:爲什麼我的Spring @Autowired字段在非控制器類的內部?

@Service 
public class ReminderServiceImpl implements ReminderService { 

@Autowired 
private RemindRepository repository; 

public Remind save(Remind remind) { 
    return repository.saveAndFlush(remind); 
} 

public List<Remind> getAll() { 
    return repository.findAll(); 
} 

} 

從控制器正常工作:

@RestController 
@RequestMapping("/api") 
public class RemindController { 

@Autowired 
private ReminderService service; 

@RequestMapping(value = "/remind", method = RequestMethod.GET, headers="Accept=application/json") 
@ResponseBody 
public List<Remind> getReminder() { 
    return service.getAll(); 
} 
} 

但是從其他類(XML解析器,例如),我得到的服務空指針異常.save(R):

@Component 
public class XMLConverter implements ResourceLoaderAware { 

@Autowired 
private ReminderService service; 

... 


public void convertFromXMLToObject() throws XmlPullParserException, IOException { 

... 
Remind r=new Remind(); 
r.setTitle(parser.getText()); 
service.save(r); 

... 

} 

} 

我的MVC-調度-servlet.xml中:

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 


<context:component-scan base-package="server"/> 

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <property name="prefix" value="/WEB-INF/"/> 
    <property name="suffix" value=".jsp"/> 
</bean> 

<jpa:repositories base-package="server.repository"/> 

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> 
    <property name="persistenceUnitName" value="myprovider"/> 
</bean> 

<tx:annotation-driven transaction-manager="transactionManager"/> 

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> 
    <property name="transactionManagerName" value="java:jboss/TransactionManager"/> 
</bean> 

我做錯了什麼?

+0

是否正確從Spring包中導入了@ Component組件? – dambros

+0

也許不是......我剛剛添加了註釋。我如何導入它? –

+0

檢查導入聲明只是爲了確保您導入正確的導入聲明。我之前輸入了錯誤的東西,花了很長時間試圖瞭解發生了什麼。 – dambros

回答

0

在哪個包是XMLConverter類?如果它不在base-package「server」之下,那麼@Autowired註釋將不起作用,導致不會掃描註解。

+0

這個類是在「服務器」包內。 –

相關問題