Framework: Spring 3.
I really can’t understand why the message source injectend in a bean ends up always to be NULL.
Here’s the snippets:
the servlet.xml
<context:annotation-config />
<context:component-scan base-package="com.myproject.controllers" />
<mvc:annotation-driven />
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
the class where the messageSource is injected
import com.myproject.controllers.forms.RegistrationForm;
@Component
public class RegistrationFormValidator implements Validator {
@Autowired
@Qualifier("messageSource")
private MessageSource messageSource;
//other stuff here...
}
here’s the controller
@Controller
@SessionAttributes("userSearchForm")
public class UsersController extends PaginationController<ProfiledUser>{
@InitBinder(value="registrationForm")
public void initBinder(WebDataBinder binder)
{
binder.setValidator(new RegistrationFormValidator());
}
I have already tried the following:
- deleting the annotations and injecting the message source via xml configuration file
- implementing the MessageSourceAware interface
- trying to inject a
ReloadableresourceBundleMessageSourceinstead of using interfaceMessageSource
everything ends up in a epic fail 😉
How can I get the MessageSource properly injected?
I think that you are examining the field values of a CGLIB classSee spring singleton bean fields are not populated
update
A general note about autowiring
@Autowiredannotation is processed byAutowiredAnnotationBeanPostProcessorwhich can be registered by specifying<context:annotation-config />annotation in the respective spring configuration file(bean postprocessors work on a per container basis so you need to have different postprocessors for the servlet and for the application root context => you need to put<context:annotation-config />both to the web app context and the dispatcher servlet configuration ).Please note that
@Autowiredannotation hasrequiredproperty which is set as default to true, that means that if the autowiring process occurs Spring will check that exactly one instance of the specified bean exists. If the bean which fields are annotated with@Autowiredis a singleton then, the check will be performed during the application initialization.update In this specific question the
Validatorinstance was not created by Spring at all, that is why no autowiring was performed and no initialization exceptions were thrown.