Reputation: 6042
(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("[email protected]");
}}
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. 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:
@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. So that it would work following way:
\\ these lines are in Controller under method
PersonValidator validator = new PersonValidator(); // my d.emailAlreadyExists("[email protected]"); is inside
validator.validate(person, bindingResult);
PersonDAO is declared in xml, but PersonValidator is not. Can't I inject Spring DAO bean into simple java object such as PersonValidator which is not delcared in xml?
(component scanning is alright by the way - just in case)
Upvotes: 0
Views: 430
Reputation: 85486
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:
@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. 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.
Upvotes: 1