简体   繁体   English

自动接线不起作用?

[英]Autowired doesn't work?

(Java Spring WebApp) (Java Spring WebApp)

I have: 我有:

public class PersonValidator implements Validator {

private PersonDAO d;

@Autowired
public void setD(PersonDAO d) {
    this.d = d;
}
public void validate(Object target, Errors errors) {
\\ some logic
d.emailAlreadyExists("testMail@test.test"); 
}}

I thought I really understand beans and autowiring - seems not. 我以为我真的很了解豆类和自动装配-似乎不是。 "d.email.." code throws me null pointer exception and it does it really with any method of PersonDAO d. “ d.email ..”代码使我抛出了空指针异常,并且确实使用PersonDAO d的任何方法来实现。 As I understand the problem is that nothing is injected. 据我了解,问题在于没有注入任何东西。

However if I try to inject it on my controller which uses this Validator everything works: 但是,如果我尝试将其注入使用此Validator的控制器上,则一切正常:

@Controller
@RequestMapping("/person")
public class PersonController
{


private PersonDAO d;

@Autowired
public void setD(PersonDAO d) {
    this.d = d;
}

 // some method with RequestMapping declaration {
    Boolean b = d.emailAlreadyExists(person.getMail());       
logger.info( b.toString());

  // } end some method

Though this code above is not what I want. 虽然上面的代码不是我想要的。 I want to inject my DAO into PersonValidator as some of DAO's methods are need to do check against db. 我想将我的DAO注入PersonValidator,因为DAO的某些方法需要针对db进行检查。 So that it would work following way: 这样它将按照以下方式工作:

 \\ these lines are in Controller under method
PersonValidator validator = new PersonValidator(); // my  d.emailAlreadyExists("testMail@test.test"); is inside
validator.validate(person, bindingResult); 

PersonDAO is declared in xml, but PersonValidator is not. PersonDAO在xml中声明,但PersonValidator未声明。 Can't I inject Spring DAO bean into simple java object such as PersonValidator which is not delcared in xml? 我不能将Spring DAO bean注入到简单的Java对象(例如PersonValidator)中,而该对象不在xml中吗?

(component scanning is alright by the way - just in case) (顺便说一句,组件扫描还可以,以防万一)

Provided that you're doing component scanning on the package in which PersonValidator is contained, it's sufficient to add the @Component annotation on top of PersonValidator class: 假设您要对包含PersonValidator的软件包进行组件扫描,则在PersonValidator类顶部添加@Component注释就足够了:

@Component
public class PersonValidator implements Validator {

Depending on your needs you may also want to change the singleton default scope: 根据您的需要,您可能还需要更改单例默认范围:

@Component
@Scope("prototype")
public class PersonValidator implements Validator {

Alternatively you can declare your PersonValidator in Spring XML. 另外,您可以在Spring XML中声明您的PersonValidator If you don't do one of these two things Spring won't even consider your Object and so nothing will get autowired in it. 如果您不执行上述两项操作之一,Spring甚至不会考虑您的对象,因此不会自动接线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM