我正在使用Spring Framework 4.0.7
关于Formatters
对于Spring MVC应用程序,我有以下内容:
@Autowired
private Set<Formatter<?>> formatters;
@Override
public void addFormatters(FormatterRegistry registry) {
for(Formatter<?> formatter : formatters){
registry.addFormatter(formatter);
}
}
工作正常。
对于Spring Web Flow我必须添加以下内容
@Bean
public DefaultFormattingConversionService conversionService(){
DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService();
for(Formatter<?> formatter : formatters){
dfcs.addFormatter(formatter);
}
return dfcs;
}
工作正常
在此之前,我可以在任何Web表单(MVC和流程)中看到,当提交或加载某些数据时formatters
完成其工作。
我的印象DefaultFormattingConversionService可以单独使用或用于测试目的(JUnit)以显示一些格式化的对象(十进制格式,即:Double&amp; BigDecimal)。
FormattingConversionService的特化,默认配置适用于大多数应用程序的转换器和格式化程序。
设计用于直接实例化,但也公开静态addDefaultFormatters(org.springframework.format.FormatterRegistry)实用程序方法,以便对任何FormatterRegistry实例进行临时使用,就像DefaultConversionService公开自己的addDefaultConverters方法一样。
根据上述内容,没有限制,只能在网络环境中应用或使用。
对于声明为conversionService()
的新独立应用程序
我有以下内容:
@Component
public class PersonService {
private static final Logger logger = LoggerFactory.getLogger(PersonService.class);
public void printPerson(Person person){
logger.info("{}", person.toString());
}
}
在主要
AnnotationConfigApplicationContext context = ...
Person person = PersonFactory.createPerson();
PersonService personService = context.getBean(PersonService.class);
personService.printPerson(person);
当我运行应用程序时,我可以看到并确认所有格式化程序已在ApplicationContext中加载,但是当打印对象时,不会执行任何类型(Double,BigDecimal)的格式化程序。
需要哪些额外配置?很明显需要一些东西
我不确定是否可行,我需要在调用.toString()
方法时,Spring以某种方式可以将formatters
应用于实体的Double BigDecimal和Date属性。
它适用于独立应用程序和测试。
答案 0 :(得分:0)
我有同样的问题。 我意识到在没有MVC的情况下测试格式化程序和转换器会带来不便,但事实证明它比我想象的要简单。
我希望我的方式也适合你。
例如:
我有一个简单的转换器。这可以从用户名转换为用户对象。
String userName - &gt;用户对象,反之亦然
测试它的解决方案:
pdfgrep -r searchterm directory
希望有所帮助!