2012-02-23 1 views
1

私は豆fooを持っていて、これにはセッターと2つの@Autowiredフィールドがあります。 setterを使用して、実行時に使用するバリデータを定義します。Springにセッターを無視させるにはどうすればいいですか?

私の問題:私はSpringで利用可能なバリデータも定義しています。

つまり、fooをインスタンス化しようとすると、IValidatorを実装するいくつかのBeanがあり、Springが自分のセッターを呼び出すために使用するものを決定できないというエラーが発生します。ダー。

Springに「この設定者を無視する」と言う方法はありますか?

[EDIT]コードは本当に簡単です:

public class AutowireTestBean { 

    // Required bean without setter 
    @Autowired 
    private TestBean autowired; 
    public TestBean getAutowired() { 
     return autowired; 
    } 

    // Standard setter. If this bean is missing, nothing bad happens 
    private OptionalBean optional; 
    public void setOptional(OptionalBean optional) { 
     this.optional = optional; 
    } 
    public OptionalBean getOptional() { 
     return optional; 
    } 
} 

XMLは次のようになります。

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:p="http://www.springframework.org/schema/p" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.0.xsd" 
     default-autowire="byType" 
     default-lazy-init="true"> 

    <bean id="bean" class="AutowireTestBean" /> 

    <bean id="autowired" class="TestBean" /> 
    <bean id="optional1" class="OptionalBean" /> 
    <bean id="optional2" class="OptionalBean" /> 

    <context:annotation-config /> 
</beans> 

これはスロー:UnsatisfiedDependencyException: Error creating bean with name 'bean' ... expected single matching bean but found 2: [optional1, optional2]

+0

@Autowiredでマークしていないと、Springはこのセッターをなぜ呼び出すのですか?あなたのコードを共有できますか? –

+0

SpringはBeanで動作するためです。内部的には、java.beans.Introspectorも使用します。 @Autowiredは、セッターを持たないプライベートフィールドを扱う場合、またはコンストラクター引数を使用する場合にのみ必要です。 –

+0

それは '@修飾子'の仕事のように聞こえるが、コードを見ることなく、それを伝えるのは難しい。 –

答えて

0

をあなたがOptionalBean@Qualifierを使用することができます会員:

@Autowired 
@Qualifier("optional1") // or optional2 
private OptionalBean optional; 

やセッター上:

@Autowired 
@Qualifier("optional1") // or optional2 
public void setOptional(OptionalBean optional) { 
    this.optional = optional; 
} 
+0

'@Qualifier("私を呼んではいけない ")(つまり、 XMLでは使用できません)。それは安全ですか?それは私の意図をより明確に述べるでしょう。しかし、私は "defaultOptional" beanを定義することもできますね: -/ –

+0

この場合、デフォルトでSpringが検索できるすべてのsetterを呼び出すので、 '@ Autowired'はオプションです。 '@ Autowired'は、セッター(プライベートフィールド)がない場合にのみ必要です。 –

+0

私は、春の構成/定義がこれを引き起こしているのは不思議です(パブリックセッターの自動autowiring)? 'default-autowire =" byType "'ですか? –

0

あなたのXMLファイルからdefault-autowire="byType"を削除します。

この場合、アノテーションのみがBeanの配線に使用されるため、@AutowiredとマークされたセッターだけがSpringによって呼び出されます。

+0

このエラーは修正されますが、注釈 '@ Required'が破られます:-( –

+1

必須であるところで自動配線を追加またはそれ以上に自動配線(必須= true) –

関連する問題