SpringBoot常用注解


常用注解

取自B站视频:https://www.bilibili.com/video/BV19K4y1L7MT?p=12&spm_id_from=pageDriver

@Configuration 与 @Bean

@Configuration
public class test{
    @Bean
    public User user1(){
        return new User("滑稽","18");
    }

    @Bean("tom")
    public Pet cat(){
        return new Pet("tomcat");
    }
}

@Configuration

告诉Springboot这是一个配置类,其作用相当于配置文件

@Configuration(proxyBeanMethods = true)
外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象

proxyBeanMethods

如果proxyBeanMethods = true (代理对象调用方法Full模式)
SpringBoot默认就会检查容器中有没有这个方法以及返回的组件如果有就拿,如果没有就新创(保持组件单实例)
如果proxyBeanMethods = false (不代理对象调用方法Lite模式)
就只是执行那个方法并不会在容器中拿取

@Bean

将类放入容器中,默认的id为方法名,也可以通过@Bean("id")的方式自定义id
方法中的返回值就是组件类型(类)

@import()

给容器自动创建组件
@Import({User.class,DBHelper.class})
//给容器自动创建了这两个组件

@Conditional

条件装配:满足Conditional指定条件,则进行组件注入

@Configuration
public class test{
    @ConditionalOnBean(name = "tom")
    //当bean中存在id为tom的实体类时才创建user1(下面的配置才生效)
    @Bean
    public User user1(){
        return new User("滑稽","18");
    }
@ConditionalOnBean(name = "tom")
 //当bean中存在id为tom的实体类时下面的配置才生效
@Configuration
public class test{
    
    @Bean
    public User user1(){
        return new User("滑稽","18");
    }

@ImportResource

导入原生配置文件

@ImportResource("xxx.xml")

配置绑定

@ConfigurationProperties

前缀定义了哪些外部属性将绑定到类的字段上  
根据 Spring Boot 宽松的绑定规则,类的属性名称必须与外部属性的名称匹配  
我们可以简单地用一个值初始化一个字段来定义一个默认值  
类本身可以是包私有的  
类的字段必须有公共 setter 方法  
@component
@ConfigurationProperties(prefix = "mycar")

public class Car{
    private String brand;
    private String Integer price;

    ...//setter方法
}

@ConfigurationProperties括号中的值为前缀在application.Properties文件中的配置如下

mycar.brand=BYD
mycar.price=100000

@EnableConfigurationProperties

@EnableConfigurationProperties(xxx.class)  
开启xxx.class的属性配置功能   
把xxx这个组件自动注册到容器中

文章作者: xucanxx
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 xucanxx !
  目录