【归纳】springboot中的IOC注解:注册bean和使用bean

目前了解的springboot中IOC注解主要分为两类:

1. 注册bean:@Component和@Repository、@Service、@Controller 、@Configuration

共同之处:这些注解都使用在类上,将类标识为Bean,由Spring扫描到后会生成一个单例bean放到容器中。

不同之处在于:

  • @Component是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层;
  • @Repository、@Service、@Controller 都包含@Component注解:
@Repository 一般修饰持久层——Dao层
@Service 一般修饰服务层(或业务层)——Service层
@Controller 通常作用在控制层——Controller层
  • @Configuration,在@Component的基础上,会对修饰的类做一个增强(利用CGLIB动态代理)。它一般用来修饰配置类——Configuration文件夹。

 

注:在类上使用以上注解后,还可以用@Bean注解修饰方法,它很明确地告诉被注释的方法产生一个Bean,然后交给Spring容器

 

2. 使用bean:@Autowired、@Resource

  • @Autowired与@Resource都可以用来装配bean, 都可以写在字段上,或写在setter方法上
  • @Autowired默认以Type方式注入
  • @Resource默认以Name方式注入,但它可以指定为Type方式(传Type值即可),也可以指定为Name和Type同时皆有的方式(那么必须找到一个Bean,它的Name和Type同时满足才可以注入)

 

 

 

示例:

注册bean

@Configuration
public
class MyBeans { @Bean("autowire") public Integer autowire_bean(){ return 1; } @Bean("resource_name1") public String resource_bean1(){ return "this is resource_bean1"; } @Bean("resource_name2") public String resource_bean2(){ return "this is resource_bean2"; } }

使用bean:

@RestController     //@RestController与@Controller有关
public class MyController {

    //@Autowired默认按类型注入,如果同一类型有多个bean就报错
    @Autowired
    private Integer autowire_bean;

    //@Resource支持name注入或type注入,或同时指定两者注入(需同时满足name和type)
    @Resource(name = "resource_name1")
    private String resource_bean1;

    @Resource(name = "resource_name2",type = String.class)
    private String resource_bean2;



    @GetMapping("/autowire_bean")
    public String getAutowire_bean(){
        return "autowire_bean: " + autowire_bean + "<br>resource_bean1: "
                + resource_bean1 + "<br>resource_bean2: " + resource_bean2;
    }

}

  

  结果:

posted @ 2019-12-24 15:21  楚不予  阅读(2932)  评论(0编辑  收藏  举报