【问题标题】:How to inject Spring's Validator implementation?如何注入 Spring 的 Validator 实现?
【发布时间】:2016-09-15 18:48:19
【问题描述】:

我开始使用 JHipster v.3.5.1 生成我的应用程序。

一段时间后,当我使用 POST 创建实体时,我需要创建验证器来对我的实体执行一些业务逻辑验证。所以我做了:

@Component
public class MyValidator implements Validator

然后,我尝试将其注入到我的控制器中(使用@RestController 注释),但无论我尝试哪种方式,它总是会导致类似的结果:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.my.app.service.domain.MyValidator] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

我尝试创建 bean 并注入它的方式

@Autowired
private MyValidator myValidator;

@Inject
private MyValidator myValidator;

@Autowired
@Qualifier("myValidator")
private MyValidator myValidator; (with @Component("myValidator") on class)

@Inject
@Qualifier("myValidator")
private MyValidator myValidator; (with @Component("myValidator") on class)

//Below was inserted in class annotated with @Configuration
@Bean
public MyValidator myValidator() {
   return new MyValidator();
}

但是我试过了 - 它失败了。我总是得到 NoSuchBeanDefinitionException 或字段值设置为 null。

我还检查了项目结构中的班级位置。为了 100% 确定它放置得当,我将它与 @Services 一起打包,经过扫描并且运行良好。没有效果。

我知道这似乎很容易,而且我知道这种注入是可能的(我已经在我的工作中看到它在项目中完成),但不知何故我无法让它在我的项目中工作。

也许我在配置中遗漏了一些东西?感谢您的帮助:)

【问题讨论】:

    标签: spring validation spring-mvc jhipster spring-validator


    【解决方案1】:

    我相信您的问题是,当您在使用 @Configuration 注释的类中使用 @Autowired 时,您只是引用了在单独的配置文件中定义的 bean,也就是说,它也必须在另一个文件中声明@Configuration 注解。

    如果您想引用另一个隐式 bean,例如使用 @Component 注释的验证器,您将需要在另一个也使用隐式符号(例如 @Component、@Service、@Controller 等)注释的隐式 bean 中执行此操作

    除非您有多个类实现相同的接口,否则单独使用 @Autowired 应该可以工作。那是你需要使用@Qualifier 的时候。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2020-08-21
    • 2012-04-02
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多