gpt4 book ai didi

java - Spring 3 @Autowired 在 Formatter 中抛出 NPE

转载 作者:行者123 更新时间:2023-12-01 15:48:42 25 4
gpt4 key购买 nike

我已经编写了自己的格式化程序并尝试将服务 Autowiring 到其中,但我收到了 NullPointerException

格式化程序:

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

格式化工厂 bean

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

所有上述类都位于 net.kurochenko.sampleapp 包内。

@Controller 中的 Autowiring 服务工作正常。我在谷歌上寻找解决方案并尝试了其中的一些,但异常仍然存在。我究竟做错了什么?感谢您的建议。

最佳答案

您很可能使用new DepartmentFormatter() 注册您的格式化程序。它不会那样工作 - spring没有机会注入(inject)依赖项。

您应该注册 spring bean 实例(由 spring 创建)。以编程方式或通过 xml 进行。

关于java - Spring 3 @Autowired 在 Formatter 中抛出 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6573073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com