Is it possible to Autowire an object in a Validation class? I keep getting null for the object that is supposed to be Autowired...
Are your Validation class an enabled Spring bean ??? If not, you always will get null for your object autowired. Make sure you have enabled your Validation class.
And do not forget enable The Annotation config bean post-processor (see
How to enable your Validation class as a managed Spring bean. Either
1° By using xml (As shown above)
2° By using annotation instead (Notice @Component just above class)
@Component
public class AccessRequestValidator implements Validator {
}
But to enable Spring annotated component scanning, you must enable a bean-post processor (notice Inside your Controller, just do it (Do not use new operator) Choose one of the following strategies UPDATE Your web app structure should looks like Your web.xml should looks like (NOTICE contextConfigLocation context-param and ContextLoaderListener) Your public class MyController implements Controller {
/**
* You can use FIELD @Autowired
*/
@Autowired
private AccessRequestValidator accessRequestValidator;
/**
* You can use PROPERTY @Autowired
*/
private AccessRequestValidator accessRequestValidator;
private @Autowired void setAccessRequestValidator(AccessRequestValidator accessRequestValidator) {
this.accessRequestValidator = accessRequestValidator;
}
/**
* You can use CONSTRUCTOR @Autowired
*/
private AccessRequestValidator accessRequestValidator;
@Autowired
public MyController(AccessRequestValidator accessRequestValidator) {
this.accessRequestValidator = accessRequestValidator;
}
}