当前位置: 移动技术网 > IT编程>开发语言>Java > 就是要让你彻底学会 @Bean 注解

就是要让你彻底学会 @Bean 注解

2019年07月12日  | 移动技术网IT编程  | 我要评论

@bean 注解全解析

随着springboot的流行,基于注解式开发的热潮逐渐覆盖了基于xml纯配置的开发,而作为spring中最核心的bean当然也能够使用注解的方式进行表示。所以本篇就来详细的讨论一下作为spring中的bean到底都有哪些用法。


@bean 基础声明

spring的@bean注解用于告诉方法,产生一个bean对象,然后这个bean对象交给spring管理。产生这个bean对象的方法spring只会调用一次,随后这个spring将会将这个bean对象放在自己的ioc容器中。

springioc 容器管理一个或者多个bean,这些bean都需要在@configuration注解下进行创建,在一个方法上使用@bean注解就表明这个方法需要交给spring进行管理。

快速搭建一个maven项目并配置好所需要的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根目录下创建一个appconfig的配置类,这个配置类也就是管理一个或多个bean 的配置类,并在其内部声明一个mybean的bean,并创建其对应的实体类

@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");
    }
}

 

在对应的test文件夹下创建一个测试类springbeanapplicationtests,测试上述代码的正确性

public class springbeanapplicationtests {
    public static void main(string[] args) {
        applicationcontext context = new annotationconfigapplicationcontext(appconfig.class);
        context.getbean("mybean");
    }
}

 

输出 : mybean initializing

随着springboot的流行,我们现在更多采用基于注解式的配置从而替换掉了基于xml的配置,所以本篇文章我们主要探讨基于注解的@bean以及和其他注解的使用。


@bean 基本构成及其使用

在简单介绍了一下如何声明一个bean组件,并将其交给spring进行管理之后,下面我们来介绍一下spring 的基本构成

@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不仅可以作用在方法上,也可以作用在注解类型上,在运行时提供注册。

  • value:name属性的别名,在不需要其他属性时使用,也就是说value 就是默认值

  • name:此bean 的名称,或多个名称,主要的bean的名称加别名。如果未指定,则bean的名称是带注解方法的名称。如果指定了,方法的名称就会忽略,如果没有其他属性声明的话,bean的名称和别名可能通过value属性配置

  • autowire :此注解的方法表示自动装配的类型,返回一个autowire类型的枚举,我们来看一下autowire枚举类型的概念

 

// 枚举确定自动装配状态:即,bean是否应该使用setter注入由spring容器自动注入其依赖项。
// 这是spring di的核心概念
public enum autowire {

  // 常量,表示根本没有自动装配。
  no(autowirecapablebeanfactory.autowire_no),
  // 常量,通过名称进行自动装配
  by_name(autowirecapablebeanfactory.autowire_by_name),
  // 常量,通过类型进行自动装配
  by_type(autowirecapablebeanfactory.autowire_by_type);

  private final int value;
  autowire(int value) {
    this.value = value;
  }
  public int value() {
    return this.value;
  }
  public boolean isautowire() {
    return (this == by_name || this == by_type);
  }
}

 

autowire的默认值为no,默认表示不通过自动装配。

initmethod: 这个可选择的方法在bean实例化的时候调用,initializationbean接口允许bean在合适的时机通过设置注解的初始化属性从而调用初始化方法,initializationbean 接口有一个定义好的初始化方法

void afterpropertiesset() throws exception;

 

spring不推荐使用initializationbean 来调用其初始化方法,因为它不必要地将代码耦合到spring。spring推荐使用@postconstruct注解或者为pojo类指定其初始化方法这两种方式来完成初始化。

不推荐使用:

public class initbean implements initializingbean {

    public void afterpropertiesset() {}
}

 

destroymethod: 方法的可选择名称在调用bean示例在关闭上下文的时候,例如jdbc的close()方法,或者sqlsession的close()方法。disposablebean 接口的实现允许在bean销毁的时候进行回调调用,disposablebean 接口之后一个单个的方法

void destroy() throws exception;

 

spring不推荐使用disposablebean 的方式来初始化其方法,因为它会将不必要的代码耦合到spring。作为替代性的建议,spring 推荐使用@predestory注解或者为@bean注解提供 destroymethod 属性。

不推荐使用:

public class destroybean {

    public void cleanup() {}
}

 

推荐使用:

public class mybean {

    public mybean(){
        system.out.println("mybean initializing");
    }

    public void init(){
        system.out.println("bean 初始化方法被调用");
    }

    public void destroy(){
        system.out.println("bean 销毁方法被调用");
    }
}

@configuration
public class appconfig {

//    @bean
    @bean(initmethod = "init", destroymethod = "destroy")
    public mybean mybean(){
        return new mybean();
    }

}

 

修改一下测试类,测试其初始化方法和销毁方法在何时会被调用

public class springbeanapplicationtests {

    public static void main(string[] args) {

        // ------------------------------ 测试一  ------------------------------
        applicationcontext context = new annotationconfigapplicationcontext(appconfig.class);
//        context.getbean("mybean");

        // 变体
        context.getbean("mybean");
        ((annotationconfigapplicationcontext) context).destroy();
//      ((annotationconfigapplicationcontext) context).close();
    }
}

 

初始化方法在得到bean的实例的时候就会被调用,销毁方法在容器销毁或者容器关闭的时候会被调用。


@bean 注解与其他注解产生的火花

在上面的一个小节中我们了解到了@bean注解的几个属性,但是对于@bean注解的功能来讲这有点太看不起bean了,@bean另外一个重要的功能是能够和其他注解产生化学反应,如果你还不了解这些注解的话,那么请继续往下读,你会有收获的。

这一节我们主要探讨@profile,@scope,@lazy,@depends-on @primary等注解

@profile 注解

@profile的作用是把一些meta-data进行分类,分成active和inactive这两种状态,然后你可以选择在active 和在inactive这两种状态下配置bean,在inactive状态通常的注解有一个!操作符,通常写为:@profile("!p"),这里的p是profile的名字。

三种设置方式:

  • 可以通过configurableenvironment.setactiveprofiles()以编程的方式激活

  • 可以通过abstractenvironment.active_profiles_property_name (spring.profiles.active )属性设置为jvm属性

  • 作为环境变量,或作为web.xml 应用程序的servlet 上下文参数。也可以通过@activeprofiles 注解在集成测试中以声明方式激活配置文件。

作用域

  • 作为类级别的注释在任意类或者直接与@component 进行关联,包括@configuration 类

  • 作为原注解,可以自定义注解

  • 作为方法的注解作用在任何方法

注意:

如果一个配置类使用了profile 标签或者@profile 作用在任何类中都必须进行启用才会生效,如果@profile({"p1","!p2"}) 标识两个属性,那么p1 是启用状态 而p2 是非启用状态的。

现有一个pojo类为subject学科类,里面有两个属性,一个是like(理科)属性,一个是wenke(文科)属性,分别有两个配置类:

一个是appconfigwithactiveprofile ,一个是appconfigwithinactiveprofile,当系统环境是 "like"的时候就注册 appconfigwithactiveprofile ,如果是 "wenke",就注册 appconfigwithinactiveprofile,来看一下这个需求如何实现

subject.java

// 学科
public class subject {

    // 理科
    private string like;
    // 文科
    private string wenke;

   get and set ...

    @override
    public string tostring() {
        return "subject{" +
                "like='" + like + ''' +
                ", wenke='" + wenke + ''' +
                '}';
    }
}

 

appconfigwithactiveprofile.java 注册profile 为like 的时候

@profile("like")
@configuration
public class appconfigwithactiveprofile {

    @bean
    public subject subject(){
        subject subject = new subject();
        subject.setlike("物理");
        return subject;
    }

}

 

appconfigwithinactiveprofile.java 注册profile 为wenke 的时候

@profile("wenke")
@configuration
public class appconfigwithinactiveprofile {

    @bean
    public subject subject(){
        subject subject = new subject();
        subject.setwenke("历史");
        return subject;
    }
}

 

修改一下对应的测试类,设置系统环境,当profile 为like 和 wenke 的时候分别注册各自对应的属性

// ------------------------------ 测试 profile  ------------------------------
annotationconfigapplicationcontext context = new annotationconfigapplicationcontext();
// 激活 like 的profile
context.getenvironment().setactiveprofiles("like");
context.register(appconfigwithactiveprofile.class,appconfigwithinactiveprofile.class);
context.refresh();
subject subject = (subject) context.getbean("subject");
system.out.println("subject = " + subject);

 

把context.getenvironment().setactiveprofiles("wenke") 设置为wenke,观察其对应的输出内容发生了变化,这就是@profile的作用,有一层可选择性注册的意味。

@scope 注解

在spring中对于bean的默认处理都是单例的,我们通过上下文容器.getbean方法拿到bean容器,并对其进行实例化,这个实例化的过程其实只进行一次,即多次getbean 获取的对象都是同一个对象,也就相当于这个bean的实例在ioc容器中是public的,对于所有的bean请求来讲都可以共享此bean。

就是要让你彻底学会 @bean 注解

那么假如我不想把这个bean被所有的请求共享或者说每次调用我都想让它生成一个bean实例该怎么处理呢?

多例bean

bean的非单例原型范围会使每次发出对该特定bean的请求时都创建新的bean实例,也就是说,bean被注入另一个bean,或者通过对容器的getbean()方法调用来请求它,可以用如下图来表示:

就是要让你彻底学会 @bean 注解

通过一个示例来说明bean的多个实例

新建一个appconfigwithaliasandscope配置类,用来定义多例的bean,

@configuration
public class appconfigwithaliasandscope {

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

 

测试一下多例的情况:

// ------------------------------ 测试scope  ------------------------------
applicationcontext context = new annotationconfigapplicationcontext(appconfigwithaliasandscope.class);
mybean mybean = (mybean) context.getbean("b1");
mybean mybean2 = (mybean) context.getbean("b2");
system.out.println(mybean);
system.out.println(mybean2);

 

除了多例的情况下,spring还为我们定义了其他情况:

就是要让你彻底学会 @bean 注解

singleton和prototype 一般都用在普通的java项目中,而request、session、application、websocket都用于web应用中。

request、session、application、websocket的作用范围

当你使用web-aware的applicationcontext应用程序上下文的时候,可以体会到 request、session、application、websocket 的作用范围,比如xmlwebapplicationcontext的实现类。

如果你使用了像是classpathxmlapplicationcontext的上下文环境时,就会抛出illegalstateexception因为spring不认识这个作用范围。

@lazy 注解

@lazy : 表明一个bean 是否延迟加载,可以作用在方法上,表示这个方法被延迟加载;可以作用在@component (或者由@component 作为原注解) 注释的类上,表明这个类中所有的bean 都被延迟加载。

如果没有@lazy注释,或者@lazy 被设置为false,那么该bean 就会急切渴望被加载;除了上面两种作用域,@lazy 还可以作用在@autowired和@inject注释的属性上,在这种情况下,它将为该字段创建一个惰性代理,作为使用objectfactory或provider的默认方法。

下面来演示一下:

@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();
    }
}

 

修改测试类

public class springconfigurationapplication {

    public static void main(string[] args) {

        annotationconfigapplicationcontext context = new annotationconfigapplicationcontext(appconfigwithlazy.class);

        // 获取启动过程中的bean 定义的名称
        for(string str : context.getbeandefinitionnames()){
            system.out.println("str = " + str);
        }
    }
}

 

输出你会发现没有关于bean的定义信息,但是当把@lazy 注释拿掉,你会发现输出了关于bean的初始化信息

@dependson 注解

指当前bean所依赖的bean。任何指定的bean都能保证在此bean创建之前由ioc容器创建。在bean没有通过属性或构造函数参数显式依赖于另一个bean的情况下很少使用,可能直接使用在任何直接或者间接使用 component 或者bean 注解表明的类上。来看一下具体的用法。

新建三个bean,分别是firstbean、secondbean、thirdbean三个普通的bean,新建appconfigwithdependson并配置它们之间的依赖关系

public class firstbean {

    @autowired
    private secondbean secondbean;

    @autowired
    private thirdbean thirdbean;

    public firstbean() {
        system.out.println("firstbean initialized via constuctor");
    }
}
 

public class secondbean {

    public secondbean() {
        system.out.println("secondbean initialized via constuctor");
    }
}
 

public class thirdbean {

    public thirdbean() {
        system.out.println("thirdbean initialized via constuctor");
    }
}
 

@configuration
public class appconfigwithdependson {

    @bean("firstbean")
    @dependson(value = {
            "secondbean",
            "thirdbean"
    })
    public firstbean firstbean() {
        return new firstbean();
    }

    @bean("secondbean")
    public secondbean secondbean() {
        return new secondbean();
    }

    @bean("thirdbean")
    public thirdbean thirdbean() {
        return new thirdbean();
    }
}

 

使用测试类进行测试,如下

// ------------------------------ 测试 dependson  ------------------------------
annotationconfigapplicationcontext context = new annotationconfigapplicationcontext(appconfigwithdependson.class);
context.getbean(firstbean.class);
context.close();

 

输出 :

secondbean initialized via constuctor
thirdbean initialized via constuctor
firstbean initialized via constuctor

由于firstbean 的创建过程首先需要依赖secondbean 和 thirdbean的创建,所以secondbean 首先被加载其次是thirdbean 最后是firstbean。

如果把@dependson 注解加在appconfigwithdependson 类上则它们的初始化顺序就会变为 firstbean、secondbean、thirdbean。

@primary 注解

指示当多个候选者有资格自动装配依赖项时,应优先考虑bean。此注解在语义上就等同于在spring xml中定义的bean 元素的primary属性。

注意:除非使用component-scanning进行组件扫描,否则在类级别上使用@primary不会有作用。如果@primary 注解定义在xml中,那么@primary 的注解元注解就会忽略,相反使用<bean primary = "true|false"/>

@primary 的两种使用方式

  • 与@bean 一起使用,定义在方法上,方法级别的注解

  • 与@component 一起使用,定义在类上,类级别的注解

通过一则示例来演示一下:

新建一个appconfigwithprimary类,在方法级别上定义@primary注解

@configuration
public class appconfigwithprimary {

    @bean
    public mybean mybeanone(){
        return new mybean();
    }

    @bean
    @primary
    public mybean mybeantwo(){
        return new mybean();
    }
}

 

上面代码定义了两个bean ,其中mybeantwo 由@primary 进行标注,表示它首先会进行注册,使用测试类进行测试

// ------------------------------ 测试 primary  ------------------------------
annotationconfigapplicationcontext context = new annotationconfigapplicationcontext(appconfigwithprimary.class);
mybean bean = context.getbean(mybean.class);
system.out.println(bean);

 

你可以尝试放开@primary ,使用测试类测试的话会发现出现报错信息,因为你尝试获取的是mybean.class,而我们代码中定义了两个mybean 的类型,所以需要@primary 注解表明哪一个bean需要优先被获取。


文章参考:

spring @profile的运用示例
https://www.javaguides.net/2018/10/spring-dependson-annotation-example.html

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网