SpringBoot 中定义 Bean 的两种方式

本贴最后更新于 2421 天前,其中的信息可能已经沧海桑田

背言

前面进行了 SpringBoot 中的注解学习

本文再单独记录一下 SpringBoot 中 Bean 两种定义方式。

Bean 定义方式

@Service

定义接口

package com.example.beandemo.bean.service; public interface EchoService { String echo(String name); }

定义实现

实现中使用了 @Service 注解

package com.example.beandemo.bean.service; import org.springframework.stereotype.Service; @Service public class ConsoleEchoService implements EchoService { @Override public String echo(String name) { return "Console: hello " + name; } }

使用

package com.example.beandemo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.beandemo.bean.service.EchoService; @RestController public class EchoController { @Autowired EchoService echoService; @RequestMapping(value = "/echo") public String echo(String name) { return echoService.echo(name); } }

效果

[note@abeffect ~]$ curl "localhost:8080/echo?name=note" Console: hello note

@Configuration 和 @Bean

实现类

实现类,注意其中没有 @Service 标签

package com.example.beandemo.bean.config; import com.example.beandemo.bean.service.EchoService; public class WebEchoService implements EchoService { @Override public String echo(String name) { return "Web: hello " + name; } }

配置类

配置类中使用了 @Bean 注解

package com.example.beandemo.bean.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.example.beandemo.bean.service.EchoService; @Configuration public class WebEchoConfig { @Bean public EchoService echoService() { return new WebEchoService(); } }

两种方式比较

@Service 中,同时完成了两件事情:

  • 实现类的创建
  • 将实现类标识为 Bean

在第二种方式中:

  • 实现类的创建:交给了单独的类
  • 将实现类标识为 Bean:通过接口名称和类的名称

即方式二中将 Bean 的标识,和类的实现过程,进行了分离。

在复杂的项目中,推荐使用第二种方式。

附录

@Component、@Repository、@Service、@Controller 区别

效果上,这四个是一样的。

注解 使用范围 备注
@Controller RequestMapping 处理相关
@Repository 存储相关
@Service 模型相关
@Component 其它相关

根据不同的 Profile 使用不同的 Bean

package com.example.beandemo.bean.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import com.example.beandemo.bean.service.EchoService; @Configuration public class WebEchoConfig { @Profile("!dev") @Bean public EchoService echoService() { return new WebEchoService(); } @Profile("dev") @Bean public EchoService mockEchoService() { return new MockWebEchoService(); } }

参考

  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3200 引用 • 8216 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...