2016-02-19 26 views
1

我有一个例子是这样的是否可以使用在同一个@Configuration类中定义的@Resource实例?

Other需要的MyBean一个实例,所以我创建一个属性,使用该属性在创建和Other

@Configuration 
public SomeClass { 

    @Resource 
    private MyBean b; 

    @Autowired 
    Environment env; 

    @Bean 
    public MyBean myBean() { 
     MyBean b = new MyBean(); 
     b.foo(env.getProperty("mb"); // NPE 
     return b; 
    } 

    @Bean 
    public Other other() { 
     Other o = new Other(o); 
     return o; 
    } 
} 

但我发现了类NullPointerException虽然初始化myBean对象,我想这是因为env属性尚未在此点连线。

如果我不使用这个bean并直接使用这个方法,那么一切正常。

@Configuration 
public SomeClass { 

    @Autowired 
    Environment env; 

    @Bean 
    public MyBean myBean() { 
     MyBean b = new MyBean(); 
     b.foo(env.getProperty("mb"); // NPE 
     return b; 
    } 

    @Bean 
    public Other other() { 
     Other o = new Other(myBean()); 
     return o; 
    } 
} 

难道是因为我确定在同一个@Configuration@Bean

+1

如果你在'b''字段中替换'@ Autowired'的'@ Resource'注解,我猜它可以正常工作吗? –

+0

@XtremeBiker好耶,工作。你能把它作为答案发布吗? – OscarRyz

回答

1

尽管它作为一个概念性问题很有趣,但Spring Java配置的方式只是将所需的bean作为参数传递,所以您应该避免将bean自动装配为配置类的字段。如果您有任何豆碰巧需要MyBean实例,只是将它作为一个参数:

@Bean 
public Other other(MyBean myBean) { 
    Other o = new Other(myBean); 
    return o; 
} 

有呼吁从配置类@Bean anotated方法也没有问题,因为你在你的第二个代码片段做,因为它们是proxied and cached,所以它们不会创建不必要的实例。但是,我倾向于遵循上面的代码,因为它允许开发人员快速了解所需的依赖关系。

话虽如此,对于您的具体问题@Autowired工作而不是@Resource,但在@Configuration类中使用它们中的任何一个都没有意义。只需使用本地方法参数。

相关问题