i've written my own formatter and tried to autowire service into it, but i'm getting NullPointerException
.
Formatter:
@Component
public class DepartmentFormatter implements Formatter<Department> {
@Autowired
private DepartmentService departmentService;
@Override
public String print(Department department, Locale locale) {
return department.getName();
}
@Override
public Department parse(String string, Locale locale) throws ParseException {
return departmentService.getByName(string); // NPE thrown here
}
}
Service:
@Service
@Transactional
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentDAO departmentDAO;
/* ... */
}
In my spring-servlet.xml i've got
<context:annotation-config />
<context:component-scan base-package="net.kurochenko.sampleapp" />
Registering of formatters:
public class FormattingFactory extends FormattingConversionServiceFactoryBean {
@Override
public void installFormatters(FormatterRegistry registry) {
super.installFormatters(registry);
registry.addFormatterForFieldAnnotation(new AuthorAnnotationFormatterFactory());
registry.addFormatterForFieldAnnotation(开发者_C百科new DepartmentAnnotationFormatterFactory());
}
}
FormattingFactory bean
<mvc:annotation-driven conversion-service="formattingFactory" />
All aforementioned classes are inside net.kurochenko.sampleapp package.
Autowiring service in @Controller
works fine. I was searching for solution on google and tried some of them, but exception still remains. What am I doing wrong? Thanks for advises.
You are most likely registering your formatter with new DepartmentFormatter()
. It won't work that way - spring doesn't get the chance to inject dependencies.
You should register the spring bean instance (created by spring). Be it programatically or via xml.
精彩评论