@Bean inside class with @Configuration and without it

后端 未结 2 848
天命终不由人
天命终不由人 2020-12-18 04:48

There is a @Bean annotation in Spring 3.0. It allows to define a Spring bean directly in a Java code. While browsing Spring reference I found two different ways

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-18 05:15

    The difference is that with @Configuration you can call one @Bean method from another and get a fully initialized instance, as follows:

    public class Foo {
        @Value("Hello, world!")
        public String value;
    }
    
    @Configuration
    public class Config {
        @Bean
        public Foo createFoo() {
            Foo foo = new Foo();
            System.out.println(foo.value); // Prints null - foo not initialized yet
            return foo;
        }
    
        @Bean
        public Bar createBar() {
            Foo foo = createFoo();
            System.out.println(foo.value); // Prints Hello, world! - foo have been initialized by the interceptor
            return new Bar(foo);
        }
    }
    

提交回复
热议问题