好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

springboot注册bean的三种方法

spring在启动时会自己把 bean (java组件)注册到ioc容器里,实现控制反转,在开发人员使用spring开发应用程序时,你是看不到new关键字的,所有对象都应该从容器里获得,它们的 生命周期 在放入容器时已经确定!

下面说一下三种注册bean的方法

@componentscan @bean @import

@componentscan注册指定包里的bean

spring容器会扫描@componentscan配置的包路径,找到标记@component注解的类加入到spring容器。

我们经常用到的类似的(注册到ioc容器)注解还有如下几个:

@configuration:配置类 @controller :web控制器 @repository :数据仓库 @service:业务逻辑

下面代码完成了emaillogserviceimpl这个bean的注册,当然也可以放在@bean里统一注册,需要看@bean那一节里的介绍。

?

1

2

3

4

5

6

7

8

9

10

@component

public class emaillogserviceimpl implements emaillogservice {

  private static final logger logger = loggerfactory.getlogger(emaillogserviceimpl. class );

 

  @override

  public void send(string email, string message) {

   assert .notnull(email, "email must not be null!" );

   logger.info( "send email:{},message:{}" , email, message);

  }

}

@bean注解直接注册

注解@bean被声明在方法上,方法都需要有一个返回类型,而这个类型就是注册到ioc容器的类型,接口和类都是可以的,介于面向接口原则,提倡返回类型为接口。

下面代码在一个@configuration注解的类中,同时注册了多个bean。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

@configuration

public class logserviceconfig {

 

  /**

   * 扩展printlogservice行为,直接影响到logservice对象,因为logservice依赖于printlogservice.

   *

   * @return

   */

  @bean

  public printlogservice printlogservice() {

   return new printlogserviceimpl();

  }

 

  @bean

  public emaillogservice emaillogservice() {

   return new emaillogserviceimpl();

  }

 

  @bean

  public printlogservice consoleprintlogservice() {

   return new consoleprintlogservice();

  }

}

@import注册bean

这种方法最为直接,直接把指定的类型注册到ioc容器里,成为一个java bean,可以把@import放在程序的八口,它在程序启动时自动完成注册bean的过程。

?

1

2

3

4

@import ({ logservice. class ,printservice. class })

public class registrybean {

 

}

spring之所以如何受欢迎,我想很大原因是它自动化注册和自动化配置这一块的设计,确实让开发人员感到非常的自如,.net里也有类似的产品,像近几年比较流行的abp框架,大叔自己也写过类似的lind框架,都是基于自动化注册和自动化配置的理念。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:http://HdhCmsTestcnblogs测试数据/lori/p/10418271.html

查看更多关于springboot注册bean的三种方法的详细内容...

  阅读:51次