從Spring XML配置樣式遷移到Spring基於Java的配置(使用@Configuration
)我遇到了一個加載資源的問題,在我的例子中是從classpath中。Spring基於Java的配置加載資源(從類路徑)
在XML我也有一顆豆聲明如下:
<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>
配置這個bean的Java類的樣子:
@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;
}
這實際上是ApplicationContext
因爲負載時拋出NullPointerException @Autowired
字段是(還沒有?)自動裝配...
問:什麼是正確的解決方案來加載資源(從c lasspath和/或一般)? Spring文檔中使用ApplicationContext
進行了推廣:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#context-introduction
問:爲什麼autowired字段仍爲空?
通常Spring允許基於Java的配置的創建通過 'ApplicationContext context = new AnnotationConfigApplicationContext(springConfig)'其中_springConfig_是對'@ Configuration'註釋配置類的引用,但我從來沒有在配置文件本身TBH中使用它,你也可以嘗試初始化編組器一個'@ PostConstruct'註釋方法在配置 – 2014-10-09 15:33:18
我開始'ApplicationContext'從單元測試使用@RunWith(SpringJUnit4ClassRunner.class)''@ContextConfiguration(classes = {AppConfig.class})'...這是否應用其他一些生命週期? – 2014-10-14 08:18:12