创建一个bean并自动装配它

时间:2013-09-14 02:27:08

标签: java spring

我目前有许多类,其中包含像

这样的字段
private MyStuff myStuff = new MyStuff();

如果有一个所有类使用的MyStuff单例,那将是更好的选择。我们的项目有一个MyConfiguration类,里面有一些Beans,但它们似乎没有被使用,至少不是直接使用,所以我不能用它们作为例子。我的任务是在MyConfiguration类中创建一个MyStuff bean,然后将它注入我的其他类。

到目前为止我所拥有的:

@Configuration
public class MyConfiguration
{
    @Bean
    public MyStuff myStuff() 
    {
        return new MyStuff();
    }
}

public SomeClass 
{
    public void dealWithStuff()
    {
        someStuff.myMethod();
    }
    @Autowired
    private MyStuff someStuff;
}

这编译但不运行。 someStuff尝试调用myMethod()时为null。显然它没有看到bean或建立连接。我错过了什么?

3 个答案:

答案 0 :(得分:1)

我要做出一个假设,如果我错了,请纠正我:你自己创建了SomeClass的实例。像

这样的东西
SomeClass someInstance = new SomeClass();

在任何Spring组件之外。

在这种情况下,你如何期望Spring注入任何东西,因为它甚至没有处理它。

你需要让Spring创建需要注入其他bean的对象(bean)。

答案 1 :(得分:0)

正如我在您的代码中看到的,您的对象引用名称是“someStuff”,但您指的是myStuff,您应该使用someStuff.myMethod();

答案 2 :(得分:0)

问题在于命名。有关完整说明,请参阅this,但简要说明

If you intend to express annotation-driven injection by name, do not primarily use @Autowired, even if is technically capable of referring to a bean name through @Qualifier values. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.

这意味着你应该做这样的事情:

@Resource(name="myStuff")
public void setSomeStuff(MyStuff someStuff){
    this.someStuff = someStuff;
}

原因是您已将bean定义为myStuff,但将其称为someStuff

同样要拥有单例实例,您只需要在Spring配置中将其范围定义为单例,如下所示:

@Configuration
public class MyConfiguration
{
    @Bean @Scope(BeanDefinition.SCOPE_SINGLETON)
    public MyStuff myStuff() 
    {
        return new MyStuff();
    }
}