1

I currently have numerous classes with a field like

private MyStuff myStuff = new MyStuff();

It would be preferable if there was a MyStuff singleton which all the classes used. Our project has a MyConfiguration class with some Beans in it, but they don't seem to get used, at least not directly, so I can't use them for examples. I have been tasked to create a MyStuff bean in the MyConfiguration class, and then inject it into my other classes.

What I have so far:

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

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

This compiles but does not run. someStuff is null when it tries to call myMethod(). Apparently it does not see the bean or make the connection. What am I missing?

4

3 回答 3

1

I'm going to make an assumption, so correct me if I'm wrong: you are creating instances of SomeClass yourself. Something like

SomeClass someInstance = new SomeClass();

outside of any Spring component.

In this case, how do you expect Spring to inject anything since it's not even process it.

You need to let Spring create objects (beans) that need to have other beans injected.

于 2013-09-15T21:14:06.157 回答
0

As I see in your code, your object reference name is "someStuff" but you are referring to myStuff you should use someStuff.myMethod();

于 2013-09-14T02:53:52.263 回答
0

The problem is naming. Refer to this for a complete description but briefly it says

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.

It means that you should be doing something like this:

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

The reason is that you have defined your bean as myStuff but referring it as someStuff.

Also to have a singleton instance, all you need is to define its scope as singleton in your Spring Configuration as following:

@Configuration
public class MyConfiguration
{
    @Bean @Scope(BeanDefinition.SCOPE_SINGLETON)
    public MyStuff myStuff() 
    {
        return new MyStuff();
    }
}
于 2013-09-14T04:15:01.907 回答