Radek
Radek

Reputation: 329

Spring /@Beans annotation

I am reading spring doc. and I am wondering what difference is between these two examples. Do I need to create Bar @bean ?

   public class AppConfig {
        @Bean
        public Foo foo() {
            return new Foo(bar());
        }

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

VS

public class AppConfig {
    @Bean
    public Foo foo() {
        return new Foo(bar());
    }

    public Bar bar() {
        return new Bar();
    }
}

Upvotes: 1

Views: 169

Answers (1)

JB Nizet
JB Nizet

Reputation: 691625

In the first one, Bar is a Spring bean, whereas in the second one, it's not.

So, if Bar must be autowired with other Spring beans, or if it has Spring annotations (like Transactional, etc.), the second example won't work as expected: the Bar instance is a simple POJO, that Spring is not aware of.

Upvotes: 3

Related Questions