preface

Beans are arguably one of the most important concepts in Spring. Simply put, a Bean is an object that is initialized, assembled, and managed by the Spring container, so it can also be called a Spring Bean. This term is inherited from Delphi and VB. Spring’s IoC and AOP-related concepts have been learned from other articles, and we’ll explore the use of Spring annotations, starting directly with Bean assembly.

To do Java well, you need to inject beans into containers.

The source code

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {
    @AliasFor("name")
    String[] value() default {};

    @AliasFor("value")
    String[] name() default {};

    / * *@deprecated* /
    @Deprecated
    Autowire autowire(a) default Autowire.NO;

    boolean autowireCandidate(a) default true;

    String initMethod(a) default "";

    String destroyMethod(a) default "(inferred)";
}
Copy the code

Note: When only one value attribute is passed in the annotation, the value attribute name can be omitted. That is, @bean (value=”myBean”) equals @bean (“myBean”); Alias stands for an Alias, so using @bean (name=”myBean”) has the same effect.

use

Normally, the @bean method is declared in the @Configuration class.

@Configuration
public class AppConfig {
    @Bean
    public FooService fooService(a) {
        return new FooService(fooRepository());
    }

    @Bean
    public FooRepository fooRepository(a) {
        return new JdbcFooRepository(datasource());
    }
    
    // ...
}
Copy the code

In the above code, we injected two beans into the Spring container, which are automatically registered as method names when not explicitly named.

Use the name attribute to explicitly name it as follows:

@Bean({"b1", "b2"}) // Bean can be fetched with 'b1' or 'b2' instead of 'myBean'
public MyBean myBean(a) {
    // Initialize and configure the MyBean object here
    return obj;
}  
Copy the code

added

Some annotations can be used in combination with @beans:

  • @ProfileAllow selective inclusion of certain beans
  • @ScopeChange the scope of the bean from a singleton to the specified scope
  • @LazyThe bean is created before it is used
  • @DependsOnSpecific other beans are created before this bean is created, as well as any dependencies that the bean represents by direct reference
  • @PrimaryUsed to resolve ambiguity at the injection point level