@Bean inside a class with and without @Configuration

Spring 3.0 has an annotation @Bean. It allows you to define a Spring bean directly in Java code. When I looked at the Spring link, I found two different ways to use this annotation: inside a class, annotated using @Configurationand inside a class that does not have this annotation.

This section contains the following code snippet:

@Component
public class FactoryMethodComponent {

   @Bean @Qualifier("public")
   public TestBean publicInstance() {
      return new TestBean("publicInstance");
   }

   // omitted irrelevant method
}

And here we could see a very similar piece of code, but now it @Configurationis in place:

@Configuration
public class AppConfig {
   @Bean
   public MyService myService() {
      return new MyServiceImpl();
   }
}

The previous section of the link contains the following explanation:

@Bean Spring , Spring @Configuration. , @Component CGLIB, . CGLIB - , @Configuration @Bean bean . Java. , @Component @Bean Java.

CGLIB - , ( , ). , Spring , @Bean Spring bean, .

, ?

+4
2

, @Configuration @Bean , :

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);
    }
}
+10

@Bean [ ] @Component. @ Bean @Bean , Java- , .. Object won 't Spring, java- factory, Component CGLIB.

@Bean [ ] @. Spring . Java-.

@Bean . @ Bean , Sterotype.

+4

Source: https://habr.com/ru/post/1756459/


All Articles