假设我有一个Singleton Spring Bean Foo。 我希望它使用http://docs.oracle.com/javase/7/docs/api/javax/xml/validation/SchemaFactory.html进行一些Schema验证 - 这不是线程安全的。如果我把不安全的方法放在我的单例bean的构造函数中,这会是一个好方法吗?正如我所看到的,bean只会被创建一次,因此CTR只会被调用一次。实质上,只有1个线程会调用不安全的代码,即创建bean的线程......
谢谢, 达明
以下完整代码: ++++++++++++++++++++++++++++++++++++++++++++++++++ +++++
public class FooImpl implements Foo {
private javax.xml.validation.Validator validator;
private JAXBContext jc;
// Exception omitted
public FooImpl() {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
jc = JAXBContext.newInstance(OrderType.class);
ClassLoader classLoader = OrderType.class.getClassLoader();
InputStream xsdStream = classLoader.getResourceAsStream("myXsd.xsd");
Source schemaSource = new StreamSource(xsdStream);
// The unsafe thread code...
// Perhaps I should synch this code...
Schema schema = schemaFactory.newSchema(schemaSource);
validator = schema.newValidator();
}
// Exception omitted
public void validateOrder(final Object in) {
validator.validate(new JAXBSource(jc, in));
}
}