Spring自定义转换器中的@Autowired

use*_*326 5 java spring spring-mvc

我有自定义转换器:

  @Component
public class RoleConverter implements Converter<String, Role> {

    @Autowired private Roles roles;

    @Override
    public Role convert(String id) {
        return roles.findById(Long.parseLong(id));
    }
}
Run Code Online (Sandbox Code Playgroud)

但是@Autowired设置为空值。造成的Nullpointerexception

这是Roles类:

@Repository
@Transactional
public class Roles extends Domain<Role>{

    public Roles() {
        super(Role.class);
    }

}
Run Code Online (Sandbox Code Playgroud)

我正在使用Java配置。转换器已注册:

@Configuration
@EnableWebMvc
//other annotations...
public class WebappConfig extends WebMvcConfigurerAdapter {
//....


    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new RoleConverter());
        super.addFormatters(registry);
    }


/....

}
Run Code Online (Sandbox Code Playgroud)

当我在控制器中使用@Autowired角色时,其工作原理。

为什么@Autowired在Converter中设置为null?

Bhu*_*ale 5

这是因为您在这里创建了一个新对象RoleConverter. 相反,您应该自动装配RoleConverter

代替

registry.addConverter(new RoleConverter());
Run Code Online (Sandbox Code Playgroud)

@Autowired
RoleConverter roleConverter;

@Override
public void addFormatters(FormatterRegistry registry)
{
    registry.addConverter(roleConverter);

}
Run Code Online (Sandbox Code Playgroud)