基于Spring Java的配置加载资源(从类路径)
从SpringXML配置风格迁移到基于SpringJava的配置(使用基于Spring Java的配置加载资源(从类路径),java,spring,autowired,applicationcontext,Java,Spring,Autowired,Applicationcontext,从SpringXML配置风格迁移到基于SpringJava的配置(使用@configuration),在从类路径加载资源时遇到了一个问题 在XML中,我有一个bean声明如下: <bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"> <property name="schema" value="classpath:/xsd/schema.xsd" /> <prop
@configuration
),在从类路径加载资源时遇到了一个问题
在XML中,我有一个bean声明如下:
<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>
这实际上会在加载ApplicationContext
期间引发NullpointerException,因为@Autowired
字段不是(尚未?)自动连接的
Q:加载资源(从类路径和/或一般情况下)的正确解决方案是什么?Spring文档中介绍了如何使用ApplicationContext
:
问:为什么自动连线字段仍然为空
marshaller.setSchema(applicationContext.getResource("classpath:/xsd/schema.xsd"));
您可以使用
marshaller.setSchema(new ClassPathResource("/xsd/schema.xsd"));
但是我无法复制您的
ApplicationContext
字段为null
,因此将ApplicationContext
自动关联到@Configuration
@Bean
方法中直接使用它似乎会产生循环自动布线情况。和一个堆栈溢出错误:-(
解决方案是使用@PostConstruct
代码中的解决方案:
@Configuration
public class AppConfig {
@Autowired
private ApplicationContext applicationContext;
@Bean
public Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.company.app.jaxb");
return marshaller;
}
@PostConstruct
public void initMarshaller() {
marshaller().setSchema(applicationContext.getResource("classpath:/xsd/schema.xsd"));
}
通常Spring允许通过ApplicationContext context=new AnnotationConfigApplicationContext(springConfig)创建基于Java的配置
其中springConfig是对@Configuration
注释的配置类的引用。但我从未在配置文件本身TBH中使用过它。您也可以尝试在配置中的@PostConstruct
注释方法中初始化封送拆收器。我正在启动ApplicationContext
使用@RunWith(SpringJUnit4ClassRunner.class)
和@ContextConfiguration(class={AppConfig.class})进行单元测试
…这是在应用其他生命周期吗?嗯..奇怪。我在beans jar中遇到了一个异常:java.lang.NoClassDefFoundError:org.springframework.beans.FatalBeanException
。我一点也不明白在注释@sotirios delimanolis中放置完整的堆栈跟踪有点困难。我可以通过使用两个bea来重现这一点一个AppConfig
配置中的ns相互依赖(循环依赖:()是的,我知道,我可能应该在这里重新考虑我的设计…;-)很高兴您找到了一个解决方案,但您的问题中绝对没有显示任何有关堆栈溢出错误的内容。此外,在@配置类中自动连接应用程序上下文本身也会导致堆栈溢出错误
。您正在做的其他事情一定没有显示出来让我们失望。
@Configuration
public class AppConfig {
@Autowired
private ApplicationContext applicationContext;
@Bean
public Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.company.app.jaxb");
return marshaller;
}
@PostConstruct
public void initMarshaller() {
marshaller().setSchema(applicationContext.getResource("classpath:/xsd/schema.xsd"));
}