2013-02-18 7 views
8

私はいくつかの奇妙な動作を見ている、私はここに誰かが問題を明るく照らすことを望んでいた。SpringのJavaConfigとCustomScopeConfigurerの問題

私のセットアップについて説明します。まず、簡単なデータがで

@Configuration 
public interface ConfigInterface { 
    public Apple getApple(); 
} 
実装するクラスでは

@Configuration 
@Import(AbstractTestConfig.class) 
public class TestConfig implements ConfigInterface { 
    public Apple getApple() { 
     return new Apple().withName("Granny apples"); 
    } 
} 

を次のように設定がある

public class Apple { 
    private String name; 
    public Apple withName(String name) { 
     this.name = name; 
     return this; 
    } 
    public String getName() { 
     return name; 
    } 
} 

とテストクラス..

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes={TestConfig.class}) 
public class AppleTest { 
    @Autowired private Apple apples; 

    @Test 
    public void simpleTest() { 
     System.out.println("OBJ: "+apples); 
    } 
} 

オブジェクト設定の依存関係...

@Configuration 
public class AbstractTestConfig { 
    @Autowired ConfigInterface conf; 

    @Bean Apple myTestApple() { 
     return conf.getApple(); 
    } 
} 

このすべては素晴らしいです。私はテストを実行する、私は期待した出力を参照してください。しかし、私はホイールにスパナを投げ、AbstractTestConfigを次のように変更します。

@Configuration 
public class AbstractTestConfig { 
    @Autowired ConfigInterface conf; 

    @Bean Apple myTestApple() { 
     return conf.getApple(); 
    } 

    // NEW CODE 
    @Bean CustomScopeConfigurer scopeConfigurer() { 
     return new CustomScopeConfigurer(); 
    } 
} 

そしてApple Beanを構築するために必要とされるとき、突然@Autowiredオブジェクトconfのすべてがnullです。

CustomScopeConfigurer beanをTestConfigクラスに移動するとさらに奇妙なことになります。

スコープや特にCustomScopeConfigurerオブジェクトについてわからないことはありますか?

答えて

16

@Bean方法に

特別な配慮をBeanFactoryPostProcessor-返すには、春BeanFactoryPostProcessor(BFPP)型を返す@Bean方法のために取られなければなりません。 BFPPオブジェクトはコンテナライフサイクルの早い段階でインスタンス化する必要があるため、@Configurationクラス内の@Autowired、@Value、および@PostConstructなどのアノテーションの処理を妨げる可能性があります。これらのライフサイクルの問題を回避するには、BFPPを返す@Beanメソッドを静的としてマークします。たとえば、次のような静的この方法をマークすることによって

@Bean 
public static PropertyPlaceholderConfigurer ppc() { 
    // instantiate, configure and return ppc ... 
} 

、したがって、上記のライフサイクルの競合を回避する、その宣言@Configurationクラスのインスタンス化を招くことなく起動することができます。ただし、静的@Beanメソッドは、前述のようにスコープとAOPのセマンティクスに対して拡張されません。 BFPPの場合は、他の@Beanメソッドでは通常参照されません。警告として、BeanFactoryPostProcessorに代入可能な戻り値の型を持つ静的でない@Beanメソッドに対してWARNレベルのログメッセージが発行されます。

0

慎重に春のログ出力を精査した後、私はこの小さな救世主に出くわしました:静的はしかし違いとして、それを持つ理由は、私は本当に理解していない

[junit] 1141 [main] WARN org.springframework.context.annotation.ConfigurationClassEnhancer - @Bean method AbstractTestConfig.scopeConfigurer is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean Javadoc for complete details 

。春@Bean javadocからコピー

関連する問題