Spring中@Component与@Bean的区别

@Component和@Bean的目的是一样的,都是注册bean到Spring容器中。

 

@Component  VS  @Bean

  @Component 和 它的子类型(@Controller, @Service and @Repository)注释在类上。告诉Spring,我是一个bean,通过类路径扫描自动检测并注入到Spring容器中。

  @Bean不能注释在类上,只能用于在配置类中显式声明单个bean。意思就是,我要获取这个bean的时候,spring要按照这种方式去获取这个bean。默认情况下@Bean注释的方法名作为对象的名字,也可以用name属性定义对象的名字。

 

所有组件类型及其用途

组件注解 用途
@Component 标注最普通的组件
@Controller 标注控制层(spring-mvc的注解)(如:*Controller)
@Service 标注业务层(如:*Service)
@Repository 标注持久层(如:*Dao)

所有组件类型都以相同的方式处理。子类型仅仅是标记,有利于代码可读性而不是特性。

 验证代码如下:

1 @Controller
2 @RequestMapping("/web")
3 public class WebController {
4     @ResponseBody
5     @RequestMapping("/msg")
6     public String message(){
7         return "msg";
8     }
9 }
1 @Component
2 @RequestMapping("/web") 3 public class WebController { 4 @ResponseBody 5 @RequestMapping("/msg") 6 public String message(){ 7 return "msg"; 8 } 9 }
1 @Service
2 @RequestMapping("/web")
3 public class WebController {
4     @ResponseBody
5     @RequestMapping("/msg")
6     public String message(){
7         return "msg";
8     }
9 }

访问url=locahost:8080/web/msg,三段代码均返回字符串msg。(此web项目我自己用的端口8080)

 

@Bean的使用

1 // Just a POJO
2 public class MessageBuilder {
3     public String getMsg(){
4         return "msgBuilder";
5     }
6 }
 1 import org.springframework.context.annotation.Bean;
 2 import org.springframework.context.annotation.Configuration;
 3 // Let's turn the POJO into a bean
 4 @Configuration
 5 public class AppConfig {
 6     @Bean
 7     public MessageBuilder messageBuilder(){
 8         return new MessageBuilder();
 9     }
10 }
 1 @Controller
 2 @RequestMapping("/web")
 3 public class WebController {
 4     // Finally, hook it up
 5     @Autowired
 6     private MessageBuilder messageBuilder;
 7 
 8     @ResponseBody
 9     @RequestMapping("/msg")
10     public String message(){
11         return messageBuilder.getMsg();
12     }
13 
14 }

 

参考文章:

http://www.tomaszezula.com/2014/02/09/spring-series-part-5-component-vs-bean/

 

posted @ 2019-09-18 15:28  zoe_java  阅读(11394)  评论(1编辑  收藏  举报