Migrating from Spring XML configuration style to Spring Java-based configuration (using @Configuration
) I run into an issue loading resources, in my case from the classpath.
In XML I did have a bean declared like:
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="schema" value="classpath:/xsd/schema.xsd" />
<property name="contextPath" value="com.company.app.jaxb" />
</bean>
Configuration this bean in a Java class looks like:
@Configuration
public class AppConfig {
@Autowired
private ApplicationContext applicationContext;
@Bean
public Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setSchema(applicationContext.getResource("classpath:/xsd/schema.xsd"));
marshaller.setContextPath("com.company.app.jaxb");
return marshaller;
}
This will actually throw a NullpointerException during loading of the ApplicationContext
because the @Autowired
field is not (yet?) autowired...
Q: What is the right solution to load resources (from the classpath and/or in general)? Using the ApplicationContext
is promoted in the Spring Documentation: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#context-introduction
Q: And why is the autowired field still null?