Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Autowired in Spring custom converter [duplicate]

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?

like image 515
user1712326 Avatar asked May 15 '13 03:05

user1712326


1 Answers

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);

}
like image 104
Bhushan Bhangale Avatar answered Oct 01 '22 11:10

Bhushan Bhangale