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/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM