@Autowired to Spring custom converter

I have a 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 sets to NULL. Nullpointerexception .

This is the role class:

 @Repository @Transactional public class Roles extends Domain<Role>{ public Roles() { super(Role.class); } } 

I am using Java configuration. Converter 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 the controller, it works.

Why does @Autowired set to null in the converter?

+4
source share
1 answer

Because here you are creating a new RoleConverter object. Instead, you should autwire RoleConverter

 registry.addConverter(new RoleConverter()); 
+4
source

Source: https://habr.com/ru/post/1480840/


All Articles