【问题标题】:@Autowired in Spring custom converter [duplicate]Spring自定义转换器中的@Autowired [重复]
【发布时间】:2013-05-09 12:27:36
【问题描述】:

我有自定义转换器:

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

    @Autowired private Roles roles;

    @Override
    public Role convert(String id) {
        return roles.findById(Long.parseLong(id));
    }
}

但是@Autowired 设置了空值。引起Nullpointerexception.

这是角色类:

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

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

}

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

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


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


/....

}

当我在控制器中@Autowired Roles 时,它的工作原理。

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

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    这是因为你在这里创建了一个RoleConverter 的新对象。相反,您应该自动连接RoleConverter

    代替

    registry.addConverter(new RoleConverter());
    

    使用

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

    【讨论】:

    • 谢谢!你说的对。我没有注意到这一点。解决了。​​
    • > 相反,您应该自动装配 RoleConverter 这到底是什么意思?
    • 救命稻草,谢谢
    猜你喜欢
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2012-09-16
    • 1970-01-01
    • 2011-07-07
    • 2017-11-24
    • 1970-01-01
    相关资源
    最近更新 更多