我有这样的服务类:
@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解析器),我得到service.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-dispatcher-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 :(得分:0)
哪个包是XMLConverter类?如果它不在基础包“server”之下,则@Autowired注释将不起作用,因为不会扫描anotations。