1
votes

I am new to using the Spring-Framework, and I am actually using the spring-boot library. I have the following question:

I understand that beans registered in the @Configuration class with @Bean are singleton by default, however I am finding that beans that rely on other beans are getting their own instances of those beans, not the singleton instance I would like them to have.

For example:


    @Bean
    public static void myFirstService() {
        return new MyFirstService(foo(), bar());
    }

    @Bean
    public static void mySecondService() {
        return new MySecondService(foo(), bar());
    }

    @Bean
    public static void foo() {
        return new Foo();
    }

    @Bean
    public static void bar() {
        return new Bar();
    }

I would like the instances of MyFirstService and MySecondService to have the same instances of foo and bar. That is what should be happening by default, right? Or am I misunderstanding something completely with how beans are handled?

I have played around with the @Scope annotation (to no avail), but it is my understanding I shouldn't have to.

Thanks in advance for any input! :)

2

2 Answers

3
votes

No sooner had I posted this, I realised the problem... (always the way...)

I figured out the answer. Just in case anyone else made the same mistake. My IDE corrected the methods to be "static", which of course they should not be.

I have changed these methods to instance methods, and everything worked as expected.

1
votes

You should have used @Autowired here as follows:

@Autowired
private MyFirstService myFirstService;

@Autowired
private MySecondService mySecondService;

And in java class code for MyFirstService and MySecondService, auto wire the foo and bar also.