2011-07-04 33 views
0

我寫過自己的格式化程序,並嘗試將自動裝入服務,但我得到NullPointerExceptionSpring 3 @Autowired在格式化程序中拋出NPE

格式化:

@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 
@Transactional 
public class DepartmentServiceImpl implements DepartmentService { 

    @Autowired 
    private DepartmentDAO departmentDAO; 

    /* ... */ 
} 

在我爲spring-servlet.xml我有

<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(new DepartmentAnnotationFormatterFactory()); 
    } 
} 

FormattingFactory豆

<mvc:annotation-driven conversion-service="formattingFactory" /> 

上述所有類net.kurochenko.sampleapp包裏面。

@Controller的自動裝配服務工作正常。我在谷歌上尋找解決方案,並嘗試了其中的一些,但異常仍然存在。我究竟做錯了什麼?感謝您的建議。

+1

你如何註冊格式化程序? – Bozho

+0

[爲什麼我的Spring @Autowired字段爲空]?(http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – chrylis

回答

2

你很可能註冊你的格式化程序new DepartmentFormatter()。它不會這樣工作 - 春天沒有得到注入依賴的機會。

你應該註冊spring bean實例(由spring創建)。以編程方式或通過xml。

相關問題