6.4 BeanオペレーションとBeanWrapperクラスの2

8269 ワード

内蔵のPropertyEditor実装
SpringはPropertyEditorsの概念を用いてObjectとStringの変換を実現する.これ(PropertyEditors)を考慮すると、オブジェクト自体よりも属性を表すのが簡単な場合があります.例えば、Dateは人間が読みやすい方法(Stringとして '2008-14-09')、元のDateに変換することもできます(または、任意の入力可読日をDateオブジェクトに変換することもできます).これは、カスタムeditors(java.beans.PropertyEditorタイプ)を登録することによって実現できます.BeanWrapperにカスタムeditorsを登録するか、指定したIoCコンテナに登録することで、プロパティを希望するタイプに変換する方法を教えます.Java.bensパッケージのJavadocでは、PropertyEditorsに関する詳細を参照できます.
Springでは、プロパティの編集に使用するいくつかの例があります.
1、beansプロパティを設定するときにPropertyEditorsを使用します.Stringが属性値としてXMLファイルに定義されている場合、Springはクラスパラメータが対応するsetメソッドにある場合、ClassEditorを使用してStringパラメータをClassオブジェクトに解析します.
2、Spring MVCフレームワークでは、複数のPropertyEditorsを使用してHTTPリクエストパラメータを解析し、CommandControlのすべてのサブクラスで手動でバインドすることもできます.
Springは、作業を簡素化するために一連のPropertyEditorsを内蔵しています.各PropertyEditorが以下にリストされ、org.springframework.beans.propertyeditorsパッケージの下にあります.ほとんどですが、次のようにすべての(以下に示す)PropertyEditorがBeanWrapperImplにデフォルトで登録されているわけではありません.どのように登録しても、デフォルト値を上書きするために独自のPropertyEditorを登録できます.
以下Springに内蔵されているPropertyEditorについては一つ一つ挙げず、いくつかの一般的なものを紹介します(翻訳者追加)
ClassEditor:StringとClassの間の変換は、もちろんStringが示すクラスが見つからないと異常と報告されます
CustomDateEditor:StringとDate間の変換は、デフォルトで登録されていません.使用する場合は、手動で登録し、適切なフォーマット形式を指定する必要があります.
CustomNumber Editor:StringとNumber(Integer、Long、Float、Double)間の変換.デフォルトで登録されていますが、上書きできます.
Spring java.beans.PropertyEditorManagerを使用して、プロパティエディタの検索パスを設定します.検索パスにはsun.bean.editorsも含まれています.このパッケージにはFont、Colorなどの多くの元のタイプ(primitive)が含まれています. types)PropertyEditorの実装.PropertyEditorクラスと標準の JavaBeansは同じパッケージの下にあり、PropertyEditorのクラス名がJavaBeansのクラス名に「Editor」を付けると、JavaBeansのインフラストラクチャはPropertyEditorのクラスを自動的に発見します(登録する必要はありません).たとえば、次のクラスとパッケージ構造は、FooEditorクラスをFooタイプのプロパティのPropertyEditorとするのに十分です.
com
  chank
    pop
      Foo
      FooEditor  // the PropertyEditorfor the Fooclass

ここでは標準のBeanInfoも使えます JavaBeansメカニズム.次の例は、BeanInfoメカニズムを使用して、1つの関連クラスの属性に対して1つ以上のPropertyEditorインスタンスを正確に登録することである.
com
  chank
    pop
      Foo
      FooBeanInfo  // the BeanInfofor the Fooclass

次はFooBeanInfoクラスのソースコードです.Fooクラスのageプロパティは、CustomNumberEditorに関連付けられます.
public class FooBeanInfo extends SimpleBeanInfo {
	public PropertyDescriptor[] getPropertyDescriptors() {
		try {
			final PropertyEditor numberPE = new CustomNumberEditor(
					Integer.class, true);
			PropertyDescriptor ageDescriptor = new PropertyDescriptor("age",
					Foo.class) {
				public PropertyEditor createPropertyEditor(Object bean) {
					return numberPE;
				};
			};
			return new PropertyDescriptor[] { ageDescriptor };
		} catch (IntrospectionException ex) {
			throw new Error(ex.toString());
		}
	}
}

追加のカスタムPropertyEditorsの登録
Stringを使用してbeanプロパティを設定すると、SpringのIoCコンテナの下部にJavaBeansが使用されます. PropertyEditorsは、Stringsをこの属性の複雑なタイプに変換します(Integerなどの単純なタイプである可能性もあります).Springには、カスタマイズされたPropertyEditorsの一部が登録されています(たとえば、classnameを本物のClassオブジェクトに変換します).また、Javaの標準JavaBeans PropertyEditor検索メカニズムを使用すると、クラスに対するPropertyEditorは適切な名前を必要とし、JavaBeansと同じパッケージの下に置くだけで自動的に見つかります.
追加のカスタムPropertyEditorsを登録する必要がある場合は、最も原始的な方法ですが、あまり便利ではありませんので、BeanFactoryの参照があると仮定すると、ConfigurableBeanFactoryインタフェースのregisterCustomEditor()メソッドを呼び出すだけでいいです.もう一つの少し便利な方法は、特殊なbeanを使うことです. factoryバックグラウンドプロセッサ (post-processor)-CustomEditorConfigurer. factory post-processorsはBeanFactoryの実装とともに使用できますが、CustomEditorConfigurerにはネストされた プロパティがインストールされているため、ApplicationContextと一緒に使用することを強くお勧めします.これは、他のbeanと同様の方法で導入でき、自動的に検出され、適用されるためです.
すべてのbeanが 义齿 contextsはBeanWrapperというものを使用して属性間の変換を処理しますが、自動的に組み込まれたpropertyを使用します. editors.BeanWrapperが登録する標準propertyについて editors、これは前節で挙げたとおりです.
また、アプリケーションコンテキストの特定のタイプについては、リソースの検索を処理するために、ある程度書き換えたり、追加の数のeditorsを追加したりすることもあります.
標準のJavaBeans PropertyEditorインスタンスは、String属性値をこの属性の真の複雑なタイプに変換するために使用されます.CustomEditorConfigurerはbeanです factory ApplicationContextに追加登録されたPropertyEditorインスタンスのサポートを簡単に追加できるpost-processor.
1つのクラスExoticTypeともう1つのクラスExoticType属性を持つDependsOnExoticTypeクラスを考慮する
package document.six.test;

public class ExoticType {
	private String name;

	public ExoticType(String name) {
		this.name = name;
	}
}
package document.six.test;

public class DependsOnExoticType {
	private ExoticType type;

	public void setType(ExoticType type) {
		this.type = type;
	}

	public ExoticType getType() {
		return type;
	}
}

すべてが確立されたら、ExoticTypeプロパティにstringを指定し、PropertyEditorにこのstringを最下位で実際のExoticTypeのインスタンスに変換させます.
	
		
	

PropertyEditorの実装は似ているように見えます:(このPropertyEditor実装は必要ありませんが、具体的にはこの記事を参照してください)
package document.six.test;

import java.beans.PropertyEditorSupport;

//converts string representation to ExoticTypeobject
public class ExoticTypeEditor extends PropertyEditorSupport {
	public void setAsText(String text) {
		setValue(new ExoticType(text.toUpperCase()));
	}
}

最後に、この新しいPropertyEditorをApplicationContextに登録するには、CustomEditorConfigurerを使用します.その後、必要に応じて使用できます.
	
		
			
				
			
		
	

PropertyEditorRegistrarsの使用
PropertyEditorRegistrarを作成し、Springコンテナにpropertyを登録する editorsの方法.いくつかの異なるシーンで同じpropertyを使用する必要がある場合 editorsでは、このインタフェースが非常に役に立ちます.たとえば、共通のregistrarを書いて、さまざまな状況で再利用します.PropertyEditorRegistrarsはPropertyEditorRegistryとともに動作し、SpringのBeanWrapper(DataBinder)はPropertyEditorRegistryというインタフェースを実現した.CustomEditorConfigurerと一緒に使用すると、PropertyEditorRegistrarsはかなり便利になります.CustomEditorConfigurerは、setPropertyEditorRegistrarsという属性を暴露しました(.):このように追加したP r e r tyEditorRegistrarsは、DataBinderおよびSpringと容易に接続できます. MVCコントローラ共有.また、editors同期をカスタマイズする問題は回避されます.P r o p e r t y EditorRegistrarは、beanの作成試行ごとに新しいP r t y Editorインスタンスを作成します.
1つの例では、PropertyEditorRegistrarの使用方法をよりよく説明することができます.まず、独自のPropertyEditorRegistrar実装を作成する必要があります.
package document.six.test;

import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;

public final class CustomPropertyEditorRegistrar implements
		PropertyEditorRegistrar {
	public void registerCustomEditors(PropertyEditorRegistry registry) {
		// it is expected that new PropertyEditorinstances are created
		registry.registerCustomEditor(ExoticType.class, new ExoticTypeEditor());
		// you could register as many custom property editors as are required
		// here...
	}
}

org.springframework.beans.support.ResourceEditorRegistrarというクラスをP r o p e r t y EditorRegistrar実装の例として学ぶことができます.この実装でregisterCustomEditors(.)メソッドが各propertyにどのように適用されるかに注意してください. editorは新しいインスタンスを作成します
次に、CustomEditorConfigurerを構成し、CustomPropertyEditorRegistrarインスタンスを注入します.
	
		
			
				
			
		
	
	

最後に、本章のテーマから少し離れて、Springを使います. MVC Webフレームワークの友人にとって、PropertyEditorRegistrarsとdata-bindingを使う SimpleFormControllerなどのControllersが一緒に作業すると便利です.次の例は、initBinder(.)の実装でPropertyEditorRegistrar(注:ここで注釈ベースのControllerであれば、initBinder(.)メソッドにも注釈@InitBinder)を1つ打つ必要がある.
public final class RegisterUserController extends SimpleFormController {
	private final PropertyEditorRegistrar customPropertyEditorRegistrar;

	public RegisterUserController(
			PropertyEditorRegistrar propertyEditorRegistrar) {
		this.customPropertyEditorRegistrar = propertyEditorRegistrar;
	}

	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		this.customPropertyEditorRegistrar.registerCustomEditors(binder);
	}
}

この方式のPropertyEditor登録は、簡潔で明瞭なコード(initBinder(.)が1行しかない)を構築し、共通のPropertyEditor登録コードを1つのクラスにカプセル化し、その後、多くのControllersで共有することを可能にするのに役立つ.