【发布时间】:2014-08-15 17:26:49
【问题描述】:
我正在尝试在 spring 配置中配置推土机。使用 xml 配置时会像
<bean class="org.dozer.spring.DozerBeanMapperFactoryBean">
<property name="mappingFiles" value="classpath*:dozer/**/*.dzr.xml"/>
</bean>
如何在配置文件中定义资源。我尝试使用ctx.getResource(),但无法访问 Configuration 类中的 ApplicationContext。
我尝试了 ContextRefreshedEvent 并从那里添加资源,但仍然没有运气。 (afterPropertiesSet 已经被调用并且添加的映射不起作用)
public class ContextRefreshedEventBuilder extends ContextRefreshedEvent {
public ContextRefreshedEventBuilder(ApplicationContext ctx) {
super(ctx);
DozerBeanMapperFactoryBean mapper = ctx.getBean(DozerBeanMapperFactoryBean.class);
try {
mapper.setMappingFiles(ctx.getResources("classpath*:dozer/**/*.dzr.xml"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
也尝试使用 ClassPathResource 但找不到正确的方法
DozerBeanMapperFactoryBean mapper = new DozerBeanMapperFactoryBean();
mapper.setMappingFiles(new Resource[]{new ClassPathResource("classpath*:dozer/**/*.dzr.xml")});
return mapper;
如何添加 ClassPathResource 作为映射位置?
---答案---
@Bean
public DozerBeanMapperFactoryBean configDozer() throws IOException {
DozerBeanMapperFactoryBean mapper = new DozerBeanMapperFactoryBean();
Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:dozer/**/*.dzr.xml");
mapper.setMappingFiles(resources);
return mapper;
}
【问题讨论】:
-
注入
ResourceLoader或ApplicationContext。用它构造一个PathMatchingResourcePatternResolver(你也可以尝试在没有上下文或资源加载器的情况下创建),并在你的模式中使用getResources方法来获取资源。 -
我不会抛出异常,如果在加载您可能不想启动应用程序的资源时出现问题,只需添加
throws IOException。 -
谢谢。好点:)
-
修改后的答案也反映了这一点。
标签: spring configuration resources classpath spring-annotations