开发者

Spring 3 @Autowired throws NPE in Formatter

开发者 https://www.devze.com 2023-03-17 08:34 出处:网络
i\'ve written my own formatter and tried to autowire service into it, but i\'m getting NullPointerException.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号