zoukankan      html  css  js  c++  java
  • spring中注解

    @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 }
    复制代码

     转载博客:https://www.cnblogs.com/zoe-java/p/11542484.html

  • 相关阅读:
    POJ 2739:Sum of Consecutive Prime Numbers(Two pointers)
    POJ 2566:Bound Found(Two pointers)
    Codeforces 528D Fuzzy Search(FFT)
    挑战程序设计竞赛 3.1 不光是查找值!“二分搜索”
    POJ 3484 Showstopper(二分答案)
    POJ 1759 Garland(二分答案)
    POJ 3662 Telephone Lines(二分答案+SPFA)
    POJ 3579 Median(二分答案+Two pointers)
    POJ 3111 K Best(二分答案)
    POJ 2976 Dropping tests(二分答案)
  • 原文地址:https://www.cnblogs.com/gaoruideboke/p/13916977.html
Copyright © 2011-2022 走看看