Detailed use annotations and @Bean

With the popularity of SpringBoot, we are now more an annotation-based configuration so as to replace the XML-based configuration, so this article focuses on our annotation-based and @Bean and other annotations;

@Bean basic concepts

  1. @Bean: Spring annotation is used to tell the @Bean method, resulting in a Bean object, and the object is to Spring Bean management. This method produces Spring Bean object only called once, then this will be the Spring Bean object in its own IOC container;
  2. SpringIOC container manages one or more of the bean, the bean need to be created in the @Configuration comment, use @Bean annotation on a method to show that this approach needs to be managed Spring;
  3. @Bean is a comment on a method level, mainly used in @Configuration annotated class, it can also be used in @Component annotated class. Add the bean id is the method name;
  4. When using Bean, i.e. is already configured in the xml file Bean brought with complete attributes, the assembly method; such @Autowired, @Resource, can byNAME (@Resource) obtained by way byTYPE (@Autowired), Bean;
  5. Registration Bean, @ Component, @Repository, @ Controller, @Service, @Configration these annotations are you to instantiate an object transformed into a Bean, on the IoC container, so when you want to use, and it will above @Autowired, @Resource fitted together, the objects, properties, methods perfect assembly;
  6. @Configuration conjunction with @Bean: @Configuration understood as a spring when the inside xml tag, @ Bean understood as a spring when the inside xml tag;

Quickly build a maven project and configure the required dependence Spring

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.3.13.RELEASE</version>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>4.3.13.RELEASE</version>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>4.3.13.RELEASE</version>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>4.3.13.RELEASE</version>
</dependency>

Src created in the root directory of a AppConfig class configuration. This configuration class that is managing one or more bean configuration class, and its declared inside a myBean of bean, and create the corresponding entity class

@Configuration
public class AppConfig {

    // 使用@Bean 注解表明myBean需要交给Spring进行管理
    // 未指定bean 的名称,默认采用的是 "方法名" + "首字母小写"的配置方式
    @Bean
    public MyBean myBean(){
        return new MyBean();
    }
}

public class MyBean {

    public MyBean(){
        System.out.println("MyBean Initializing");
    }
}

Then create a test class SpringBeanApplicationTests, test the correctness of the above code

public class SpringBeanApplicationTests {

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        context.getBean("myBean");
    }
}

Output: MyBean Initializing

In-depth understanding @Bean annotated 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 {};
    Autowire autowire() default Autowire.NO;
    String initMethod() default "";
    String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;
}

@Bean attributes:

  1. value: bean alias name is interdependent and related, value, then the value of name if the use must be consistent;
  2. name: bean name, if you do not write notes will default to the name of the method;
  3. autowire: assembling custom default is not turned on, not recommended to open, because the automatic assembly of the basic data types can not be fitted, strings, arrays, etc. This is a limitation of the design of automatic assembly and automatic assembly accuracy is better dependency injection;
  4. initMethod: performing initialization bean previous methods, which do not use general parameters, as can be implemented in code;
  5. destroyMethod: javaConfig default configuration bean, if close or shutdown methods exist, the method will be automatically executed when the bean destroyed, if you do not want to execute the method, add @Bean (destroyMethod = "") to prevent the departure destruction method;
  • If you find destruction method is not performed because the bean ecstasy before the program is over, you can manually close down as follows:
		AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(MainConfig.class);
        User bean2 = applicationContext2.getBean(User.class);
        System.out.println(bean2);
        //手动执行close方法
        applicationContext2.close();

Results are as follows:

Before the user performs initialization bean
User [userName = John Doe, age = 26]
performed after destruction bean

We found @baen annotation @Target is ElementType.METHOD, ElementType.ANNOTATION_TYPE also said @Bean annotation can be used on a method, and an annotation type declaration

@Bean notes used in conjunction with other notes

@Bean comment more than these attributes, and it can be used in conjunction with other comments, please continue to read:

@Profile annotation
action @Profile some of the meta-data is to be classified, and divided into Active InActive two states, then you can select and active configuration in Inactive state both the bean, the Inactive state normally has a comment ! Operator, usually written as: @Profile ( "! P") , p here is Profile name.

Set of three ways:

  • () Can be activated in a programmed manner by ConfigurableEnvironment.setActiveProfiles.
  • JVM attributes may AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME (spring.profiles.active) property.
  • As an environment variable, or as a Servlet web.xml application context parameter. You can also activate @ActiveProfiles comment declaratively in the configuration file integration testing.

Scope:

  • As a class-level annotation or directly in any type @Component associated class comprises @Configuration
  • As the original notes, annotations can be customized
  • As a method of annotation role in any method

Note:
If a configuration class uses the Profile label or @Profile role must be enabled to take effect in any class, if @Profile ({ "p1", " ! P2"}) identifies two attributes, then p1 is p2 enabled and non-enabled state.

E.g:

	@Profile("dev")
    public @Bean("activityMongoFactory")
    MongoDbFactory activityMongoFactoryDev(MongoClient activityMongo) {
        return new SimpleMongoDbFactory(activityMongo, stringValueResolver.resolveStringValue("${mongodb.dev.database}"));
    }

@Scope comment

In Spring default processing for the bean are single embodiment, we get the context bean container vessel .getBean methods, and be instantiated, the instance of the process is actually only once, i.e. multiple object acquired getBean are the same object, it is equivalent to the bean instance is in the public IOC container, for all requests in terms of bean can share this bean.

  • If we do not want to put this bean is shared by all of the requests or that every call I want to make it generate a new bean instance, how to achieve it?

Examples of the plurality of the bean

Are created when non-singleton bean prototype range will make the request to a specific bean bean instance every time that a new, i.e., another bean bean is injected, or by getBean container () method invocation request it .

  • Here, we have multiple instances will be explained by an example of the bean

Create a new ConfigScopeconfiguration class, it is used to define multiple embodiments bean

@Configuration
public class ConfigScope {

    /**
     * 为myBean起两个名字,b1 和 b2
     * @Scope 默认为 singleton,但是可以指定其作用域
     * prototype 是多例的,即每一次调用都会生成一个新的实例。
     */
    @Bean({"b1","b2"})
    @Scope("prototype")
    public MyBean myBean(){
        return new MyBean();
    }
}

Note : the representative prototype bean object defined as an object of any number of instances, it may be designated as the prototype property defined as a multi embodiment, each call will also generate a new instance.

Scope Detailed
singleton The default singleton bean definition information for each container, the IOC are singletons
prototype Bean objects defined for any number of object instances
request Define the bean object to an HTTP request life cycle, that is, each HTTP request has its own bean instance, it is created in the back of a single bean definition. Is valid only in the context of web-aware
session Bean object defined as a life cycle of HTTP sessions. Is valid only in the context of web-aware
application The definition of bean objects in the ServletContext lifecycle. Is valid only in the context of web-aware
websocket Bean object definitions within WebSocket life cycle. Is valid only in the context of web-aware

singleton and prototype are generally used in ordinary Java project, and request, session, application, websocket are used in web applications.

@Lazy comment

Indicate whether a delay bean loading, may act on the method, this method is showing delayed loading; @Component may act on (as original or annotated by the @Component) annotation class, this class indicates that all of the bean are delayed loading . If there is no comment @Lazy or @Lazy is set to false, then the bean will be loaded urgent desire; in addition to the above two scopes, @ Lazy may also act on the properties and @Inject @Autowired annotations, in which case, it creates an inert agent that field, as the default method of ObjectFactory or Provider. Let's show you:

@Lazy
@Configuration
@ComponentScan(basePackages = "com.spring.configuration.pojo")
public class AppConfigWithLazy {

    @Bean
    public MyBean myBean(){
        System.out.println("myBean Initialized");
        return new MyBean();
    }

    @Bean
    public MyBean IfLazyInit(){
        System.out.println("initialized");
        return new MyBean();
    }
}

@Primary comment

Indicating when a plurality of candidates eligible automatic assembly dependencies, priority should be given bean. This annotation is semantically equivalent to the primary property bean element defined in the Spring XML. Note: Unless component scans using component-scanning, or use @Primary will not have a role at the class level. If @Primary annotations defined in XML, then @Primary comments yuan notes will be ignored, on the contrary, then you can take priority.

@Primary of two ways:

  • Used with @Bean, defined in the method, the method level annotations
  • Used with @Component, defined at the class, the class-level annotations

AppConfigWithPrimary a new class, defined at the method level annotation @Primary

@Configuration
public class AppConfigWithPrimary {

    @Bean
    public MyBean myBeanOne(){
        return new MyBean();
    }

    @Bean
    @Primary
    public MyBean myBeanTwo(){
        return new MyBean();
    }
}

The above two code defines the bean, which are labeled by the myBeanTwo @Primary, indicating that it will first register, for testing with the test class

Spring Bean's life cycle specific details link:
https://blog.csdn.net/weixin_42140261/article/details/104615844

Published 51 original articles · won praise 11 · views 6076

Guess you like

Origin blog.csdn.net/weixin_42140261/article/details/104864333