簡體   English   中英

自動接線不起作用?

[英]Autowired doesn't work?

(Java Spring WebApp)

我有:

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

我以為我真的很了解豆類和自動裝配-似乎不是。 “ d.email ..”代碼使我拋出了空指針異常,並且確實使用PersonDAO d的任何方法來實現。 據我了解,問題在於沒有注入任何東西。

但是,如果我嘗試將其注入使用此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

雖然上面的代碼不是我想要的。 我想將我的DAO注入PersonValidator,因為DAO的某些方法需要針對db進行檢查。 這樣它將按照以下方式工作:

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

PersonDAO在xml中聲明,但PersonValidator未聲明。 我不能將Spring DAO bean注入到簡單的Java對象(例如PersonValidator)中,而該對象不在xml中嗎?

(順便說一句,組件掃描還可以,以防萬一)

假設您要對包含PersonValidator的軟件包進行組件掃描,則在PersonValidator類頂部添加@Component注釋就足夠了:

@Component
public class PersonValidator implements Validator {

根據您的需要,您可能還需要更改單例默認范圍:

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

另外,您可以在Spring XML中聲明您的PersonValidator 如果您不執行上述兩項操作之一,Spring甚至不會考慮您的對象,因此不會自動接線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM