zoukankan      html  css  js  c++  java
  • 【java框架】SpringBoot(2) -- SpringBoot主要注解说明

    1.SpringBoot涉及注解配置说明

    1.1. @Configuration与@Bean注解

    @Configuration(proxyBeanMethods = true)

    • 用于声明该类是SpringBoot的一个配置类,它有一个参数proxyBeanMethods默认是true,表示Full模式,该配置下由Spring管理配置创建的Bean都是单例的
    • 当proxyBeanMethods设置为false时,每个Bean方法被调用一次就会生成一个新创建的Bean对象

    @Bean

    • 用于表示该方法会返回一个Bean实例,声明该实例是被Spring管理,即注解代替了配置于xml中的bean
    /**
     *   1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
     *   2、配置类本身也是组件
     *   3、proxyBeanMethods:代理bean的方法
     *     Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
     *     Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
     *     组件依赖必须使用Full模式默认。其他默认是否Lite模式
     */
    @Configuration(proxyBeanMethods = true)  //告诉SpringBoot这是一个配置类,和配置文件的作用一样
    public class MyConfig {
        @Bean  //给容器中添加组件,以方法名作为组件id
        //返回类型就是组件类型,返回的值,就是组件在容器中的实例
        public User user01() {
            User zhangsan = new User("zhangsan", 19);
            //user组件依赖了Pet组件
            zhangsan.setPet(tomcat());
            return zhangsan;
        }
    
        @Bean(name = "tom")
        public Pet tomcat() {
            return new Pet("tomcat");
        }
    }

    1.2.@Import注解

    @Import:用于配置类或其它组件类之上,可以给对应类中创建出{"A.class", "B.class"}  A和B两个类型的对象。

    @Import({DBHelper.class, ModelAndView.class})   //给容器中自动创建出这两个类的对象
    public class MyConfig {
        。。。。 
    }

    1.3.@Conditional注解

    @Confitional:条件装配,满足指定的条件,才进行容器的注入,否则不进行容器化组件注入。

    @ConditionalOnBean:当容器中有某个名字的Bean存在时,当前的Bean才创建。

    @ConditionalOnMissingBean:当容器中没有某个名字的Bean存在时,当前的Bean才创建。

    =====================测试条件装配==========================
    @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
    //@ConditionalOnBean(name = "tom")
    @ConditionalOnMissingBean(name = "tom")
    public class MyConfig {
        @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
        public User user01(){
            User zhangsan = new User("zhangsan", 18);
            //user组件依赖了Pet组件
            zhangsan.setPet(tomcatPet());
            return zhangsan;
        }
    
        @Bean("tom22")
        public Pet tomcatPet(){
            return new Pet("tomcat");
        }
    }
    
    public static void main(String[] args) {
            //1、返回我们IOC容器
            ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
    
            //2、查看容器里面的组件
            String[] names = run.getBeanDefinitionNames();
            for (String name : names) {
                System.out.println(name);
            }
    
            boolean tom = run.containsBean("tom");
            System.out.println("容器中Tom组件:"+tom);
    
            boolean user01 = run.containsBean("user01");
            System.out.println("容器中user01组件:"+user01);
    
            boolean tom22 = run.containsBean("tom22");
            System.out.println("容器中tom22组件:"+tom22);
    }

    1.4.@ImportResource注解

    @ImportResource:用于引入其它配置项文件,比如classpath配置中原生的bean文件,可以将项目中原来xml配置中的bean文件导入到现有的类中。

    @ImportResource(locations = "classpath:bean.xml")

    1.5.配置绑定

    配置绑定可以将application.properties或者application.yaml中配置的Bean属性以"prefix"、"value"绑定到对应的Bean对象本身。配置绑定有两种方式:

    ①在对应被绑定的Bean上使用注解@Component、@ConfigurationProperties(prefix = "绑定前缀");

    @Component //必须声明该类是属于Spring容器管理的类
    @ConfigurationProperties(prefix = "myproduct")  //声明此类是在配置文件中的属性,并且属性前缀是myproduct
    public class Product {
    
        private String brand;
    
        private String price;
    
    }

    ②使用@EnableConfigurationProperties(注入类.class)与@ConfigurationProperties(prefix = "绑定前缀");

    @EnableConfigurationProperties(Product.class)
    public class MyConfig {
        @Bean(name = "tom22")  //给容器中添加组件,以方法名作为组件id
        //返回类型就是组件类型,返回的值,就是组件在容器中的实例
        @ConditionalOnBean(name = "tom22")
        public User user01() {
            User zhangsan = new User("zhangsan", 19);
            //user组件依赖了Pet组件
            zhangsan.setPet(tomcat());
            return zhangsan;
        }
    
        @Bean(name = "tom22")
        public Pet tomcat() {
            return new Pet("tomcat");
        }
    }
    @ConfigurationProperties(prefix = "myproduct")  //声明此类是在配置文件中的属性,并且属性前缀是myproduct
    public class Product {}

    application.properties配置:

    #配置实体名称对应值
    myproduct.brand=xiaomi
    myproduct.price=1300

    ③除此两种方式之外,也可以使用@PropertySource(value = "classpath:mydefined.properties")与@Value组合取值(需要一个个注解设置,不推荐):

    @PropertySource(value = "classpath:mydefined.properties")
    public class Person {
        //SPEL表达式取出配置文件的值
        @Value("${username}")  //将properties文件中配置的值赋值给userName实体属性
        private String userName;
    
    }

    1.6.JSR303校验

    JSR303校验用于POJO对应的一些属性,比如年龄、邮箱等需要进行数据格式验证的内容,可以使用@Validated、@Email、@Max等注解进行格式检测:

    主要的注解配置如下:

    @Validated
    public class Person {
        @Max(value = 60, message = "年龄最大不能超过60岁")
        private Integer age;
        @Email
        private String email;
    }

    常用的JSR303注解:

    空检查

    • @Null:验证对象是否为null
    • @NotNull:对象是否不为null,无法检查长度为0的字符串
    • @NotBlank:字符串必须不为Null,且去掉前后空格长度必须大于0。只对字符串,且会去掉前后空格
    • @NotEmpty:检查约束元素是否为Null或者Empty

    Boolean

    • @AssertTrue:验证Boolean对象是否为true
    • @AssertFalse:验证Boolean对象是否为false

    长度检查

    • @Size(min= ,max= ):对象(Array、Collection、Map、String)长度必须在给定范围内
    • @Length(min= ,max= ):验证String长度在给定的范围内

    数字检查

    • @Max(value,  message):必须为数字,且小于或等于Value
    • @Min(value, message):必须为数字,且大于或等于Value
    • @DecimalMax(Value):必须为数字( BigDecimal ),且小于或等于Value。小数存在精度
    • @DecimalMin(Value):必须为数字( BigDecimal ),且大于或等于Value。小数存在精度
    • @Digits(integer,fraction):必须为数字( BigDecimal ),integer整数精度,fraction小数精度

    日期检查

    • @Past:验证Date和Calendar对象是否在当前时间之前
    • @Future:验证Date和Calendar对象是否在当前时间之后

    特殊格式检查

    • @Email:字符串必须是合法邮件地址
    • @Pattern:验证String对象是否符合正则表达式的规则

    2.yaml配置

    2.1.yaml简介

    YAML 是 "YAML Ain't Markup Language"(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)。

    YAML非常适合用来做以数据为中心的配置文件。

     

    2.2.yaml基本语法

    • key: value;kv之间有空格
    • 大小写敏感
    • 使用缩进表示层级关系
    • 缩进不允许使用tab,只允许空格(IDEA中已经由工具处理)
    • 缩进的空格数不重要,只要相同层级的元素左对齐即可
    • '#'表示注释
    • 字符串无需加引号,如果要加,''与""表示字符串内容 会被 转义/不转义(使用""中的 在打印输出时会换行输出

     

    2.3.数据类型

    字面量:单个的、不可再分的值。date、boolean、string、number、null

    k: v

    对象:键值对的集合。map、hash、set、object 

    行内写法:  k: {k1:v1,k2:v2,k3:v3}
    #或
    k: 
      k1: v1
      k2: v2
      k3: v3

    数组:一组按次序排列的值。array、list、queue

    行内写法:  k: [v1,v2,v3]
    #或者
    k:
      - v1
      - v2
      - v3    

    2.4.使用示例

    ①编写实体类型:

    @Data
    public class Person {
        
        private String userName;
        private Boolean boss;
        private Date birth;
        private Integer age;
        private Pet pet;
        private String[] interests;
        private List<String> animal;
        private Map<String, Object> score;
        private Set<Double> salarys;
        private Map<String, List<Pet>> allPets;
    }
    
    @Data
    public class Pet {
        private String name;
        private Double weight;
    }

    ②配置application.yaml格式:

    person:
      userName: zhangsan  # String
      boss: true  # Boolean
      birth : 1990/1/12  # Date
      age: 30  # Integer
      pet:  # Pet
        name: 阿杰  # String
        weight: 43  # double
      interests: [足球, 篮球, 游泳]  # String[]
      animal:  # List<String>
        - jerry
        - mario
      score:   # Map<String, Object>
        chinese:
          first: 30
          second: 49
          third: 56
        math: [134, 145, 149]
        english: {first: 120, second: 135}
      salarys: [3999, 4999.98, 5999.99]  # Set<Double>
      allPets:  # Map<String, List<Pet>>
        sick:
          - {name: tom, weight: 32}
          - {name: jerry,weight: 47}
        health: [{name: mario,weight: 47}]

    2.5.yaml编写提示配置

    为了在编写yaml有类自动提示功能,需要在pom.xml中增加spring-boot-configuration-processor功能:

    <!--增加配置提示器processor-->
    <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-configuration-processor</artifactId>
          <optional>true</optional>
    </dependency>
    
    <build>
        <plugins>
            <!--springboot maven依赖:简化部署打包-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!--编译时去除processor打包依赖-->
                    <excludes>
                        <exclude>
                                <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

    2.6.yaml多环境配置

    server:
      port: 8081
    spring:
      profiles:
        active: devlop
    
    ---
    server:
      port: 8082
    spring:
      profiles: devlop
    
    ---
    server:
      port: 8083
    spring:
      profiles: product

    本博客写作参考文档相关:

    https://www.yuque.com/atguigu/springboot/rg2p8g

    https://spring.io/projects/spring-boot

    https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-starter

    示例代码已上传至Github地址:

    https://github.com/devyf/SpringBoot_Study/tree/master/helloword_create

  • 相关阅读:
    菜鸟学存储:网络存储IP SAN与IB SAN
    读xml高手
    预先加载图片
    xred520
    最简单准确的硬盘整数分区设置操作方法
    Google 每天处理约 20000TB 的数据
    IE 8 无法正常使用网站后台编辑器问题
    常用的JS技术1
    adodb stream 使用说明
    [Tools] JDGUI(Java Decompiler)
  • 原文地址:https://www.cnblogs.com/yif0118/p/14551655.html
Copyright © 2011-2022 走看看