我们在Spring Boot应用程序中定义了一个XStreamMarshaller作为@Bean。
@SpringBootApplication
public class MyApplication extends WebMvcConfigurerAdapter {
// ...
@Bean
public XStreamMarshaller xStreamMarshaller() {
XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();
Class<?>[] annotatedClasses = { MyAnnotatedClass.class };
xStreamMarshaller.setAnnotatedClasses(annotatedClasses);
NameCoder nameCoder = new XmlFriendlyNameCoder();
xStreamMarshaller.setNameCoder(nameCoder);
xStreamMarshaller.getXStream().ignoreUnknownElements();
return xStreamMarshaller;
}
}
它自动装入JUnit测试:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { MyApplication.class })
public class MyAnnotatedClassTest {
@Autowired
private XStreamMarshaller xStreamMarshaller;
// ...
}
在调试器中检查它时,构造它时xStreamMarshaller.xstream.fieldAliasingMapper.unknownFieldsToIgnore = [.*]
检查自动装配的实例(具有相同的对象ID)时,xStreamMarshaller.xstream.fieldAliasingMapper.unknownFieldsToIgnore = []
为什么它会丢失unknownFieldsToIgnore
设置以及如何强制保留该设置?
修改
Per @indyaah,我已将bean定义移到:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "my.application" })
public class MvcConfiguration extends WebMvcConfigurerAdapter {
// ...
@Bean
public XStreamMarshaller xStreamMarshaller() {
XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();
Class<?>[] annotatedClasses = { MyAnnotatedClass.class };
xStreamMarshaller.setAnnotatedClasses(annotatedClasses);
NameCoder nameCoder = new XmlFriendlyNameCoder();
xStreamMarshaller.setNameCoder(nameCoder);
xStreamMarshaller.getXStream().ignoreUnknownElements();
return xStreamMarshaller;
}
}
并使我的Spring Boot Application文件非常薄:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
这仍然具有与重构之前相同的行为。