I have custom converter:
  @Component
public class RoleConverter implements Converter<String, Role> {
    @Autowired private Roles roles;
    @Override
    public Role convert(String id) {
        return roles.findById(Long.parseLong(id));
    }
}
But @Autowired is setting null value. Causing Nullpointerexception.
This is Roles class:
@Repository
@Transactional
public class Roles extends Domain<Role>{
    public Roles() {
        super(Role.class);
    }
}
I'm using Java Configuration. Converter is registered:
@Configuration
@EnableWebMvc
//other annotations...
public class WebappConfig extends WebMvcConfigurerAdapter {
//....
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new RoleConverter());
        super.addFormatters(registry);
    }
/....
}
When I @Autowired Roles in controller its works.
Why @Autowired is setting null in Converter?
It is because here you are creating a new object of RoleConverter. Instead you should autowire the RoleConverter
Instead of
registry.addConverter(new RoleConverter());
Use
@Autowired
RoleConverter roleConverter;
@Override
public void addFormatters(FormatterRegistry registry)
{
    registry.addConverter(roleConverter);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With