zoukankan      html  css  js  c++  java
  • SpringBoot中IOC注解

    目前了解的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容器

     !!!注意坑:

      当你使用@Bean注册的bean给SpringBoot框架使用时,方法名必须要与接口名或者类名一致才可以生效。如果是自己注册的bean给自己用的话就可以随便起

    // 自动装配到SpringBoot中
        @Bean
        public LocaleResolver localeResolver() {
            return new MyLocaleResolver();
        }
    // 这里 LocaleResolver 是springboot中的接口,所以方法名必须是localeResolver 不然注册不了

      

    spring-boot推荐的编程思想是约定优于配置,这些固定名字的bean名字,就是这种编程思想的体理。必须叫这些约定俗成的名字。如果你改成别的名字,程序就无法成功运行。
    1、如果是给框架使用的就要用约定的名字,但如果写出来的bean是给自己使用的,就可以随便写,
    就比如说这里的redis2Template名字,就是因为这个bean仅仅是用来给我自己在controller调用,所以并不需要按照约定的名字写

    @Bean(name = "redis2Template")
    public RedisTemplate<String, Object> redis2Template() throws Exception {}

    2、但是像这个dataSource就是为了给框架使用的,所以不能随便写名字

    @Bean(initMethod = "init", destroyMethod = "close")
    @Primary
    public DataSource dataSource() throws SQLException {}

    3. 使用bean:@Autowired、@Resource

    • @Autowired与@Resource都可以用来装配bean, 都可以写在字段上,或写在setter方法上
    • @Autowired默认以Type方式注入
    • @Resource默认以Name方式注入,但它可以指定为Type方式(传Type值即可),也可以指定为Name和Type同时皆有的方式(那么必须找到一个Bean,它的Name和Type同时满足才可以注入)
  • 相关阅读:
    Leetcode Binary Tree Level Order Traversal
    Leetcode Symmetric Tree
    Leetcode Same Tree
    Leetcode Unique Paths
    Leetcode Populating Next Right Pointers in Each Node
    Leetcode Maximum Depth of Binary Tree
    Leetcode Minimum Path Sum
    Leetcode Merge Two Sorted Lists
    Leetcode Climbing Stairs
    Leetcode Triangle
  • 原文地址:https://www.cnblogs.com/lpss-75074038/p/13415871.html
Copyright © 2011-2022 走看看