• SpringBoot底层注解总结


    @Configuration与@Import

    1. @Import({User.class, DBHelper.class})
    2. @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
    3. public class MyConfig {
    4. }

    @Configuration:告诉SpringBoot这是一个配置类,等同于 配置文件

    @Import({User.class, DBHelper.class})给容器中自动创建出这两个类型的组件、默认组件名字是全类名

    @Conditional条件装配

    1. @Configuration(proxyBeanMethods = false)
    2. @ConditionalOnMissingBean(name = "tom")//没有tom名字的Bean时,MyConfig类的Bean才能生效。
    3. public class MyConfig {
    4. }

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

    没有tom名字的Bean时,MyConfig类的Bean才能生效。

    @ImportResource导入Spring配置文件

    若项目原来用bean.xml文件生成配置bean,想继续复用bean.xml,可用@ImportResource

    bean.xml:

    1. "1.0" encoding="UTF-8"?>
    2. <beans ...">
    3. <bean id="haha" class="com.yhd.boot.bean.User">
    4. <property name="name" value="liming">property>
    5. <property name="age" value="18">property>
    6. bean>
    7. beans>

    使用方法:

    1. @ImportResource("classpath:beans.xml")
    2. public class MyConfig {
    3. ...
    4. }

    @ConfigurationProperties配置绑定

    使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用

    传统方法:

    1. public class getProperties {
    2. public static void main(String[] args) throws FileNotFoundException, IOException {
    3. Properties pps = new Properties();
    4. pps.load(new FileInputStream("a.properties"));
    5. Enumeration enum = pps.propertyNames();//得到配置文件的名字
    6. while(enum.hasMoreElements()) {
    7. String strKey = (String) enum1.nextElement();
    8. String strValue = pps.getProperty(strKey);
    9. System.out.println(strKey + "=" + strValue);
    10. //封装到JavaBean
    11. }
    12. }
    13. }

    Spring Boot配置绑定方法:

    第一种:@ConfigurationProperties + @Component

    有配置文件application.properties:

    1. mycar.brand=BYD
    2. mycar.price=100000
    1. @Component
    2. @ConfigurationProperties(prefix = "mycar")
    3. public class Car {
    4. ...
    5. }

    第二种:@EnableConfigurationProperties + @ConfigurationProperties

            开启Car配置绑定功能

    1. @EnableConfigurationProperties(Car.class)
    2. public class MyConfig {
    3. ...
    4. }

            把这个Car这个组件自动注册到容器中

    1. @ConfigurationProperties(prefix = "mycar")
    2. public class Car {
    3. ...
    4. }

  • 相关阅读:
    部署LVS-DR集群+keepalived(主-备)
    深入理解左倾红黑树 | 京东物流技术团队
    08 nginx 的一次请求处理调试
    用通俗易懂的大白话彻底搞明白mysql的数据类型以及mysql中的int(11),这个11到底是啥?
    每天一道算法题:46. 全排列
    需要SMB签名的漏洞解决方案
    闭区间上连续函数的一些定理
    详解Python3对json和txt文件的读写操作
    流式结构化数据计算语言的进化与新选择
    工作两年,没想到靠Python搞副业让我实现了财务自由
  • 原文地址:https://blog.csdn.net/m0_38071129/article/details/126867135