• @EnableAutoConfiguration 标签使用


    @EnableAutoConfiguration 这个注解的作用是:

    从classpath中搜索所有META-INF/spring.factories配置文件然后,将其中org.springframework.boot.autoconfigure.EnableAutoConfiguration key对应的配置项加载到spring容器

    下面介绍一下这个标签的用法,这个标签是 包含在 SpringBootApplication  这个注解中的。

    @SpringBootConfiguration
    @EnableAutoConfiguration
    @ComponentScan(
        excludeFilters = {@Filter(
        type = FilterType.CUSTOM,
        classes = {TypeExcludeFilter.class}
    ), @Filter(
        type = FilterType.CUSTOM,
        classes = {AutoConfigurationExcludeFilter.class}
    )}
    )
    public @interface SpringBootApplication {

    1.首先 我们定一个 Demo类。

    package com.example.demo;
    
    public class Demo {
    
        public String hello(){
            return  ("hello world");
        }
    }

    2.定义一个配置类。

    package com.example.demo;
    
    import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnJava;
    import org.springframework.boot.system.JavaVersion;
    import org.springframework.context.annotation.Bean;
    
    //@ConditionalOnBean(name = "operaSinger1")
    //@ConditionalOnJava(range = ConditionalOnJava.Range.EQUAL_OR_NEWER,value = JavaVersion.EIGHT)
    public class DemoAutoConfigure1 {
    
        @Bean
        private Demo demo(){
            return  new Demo();
        }
    }

    这里我们产生一个Demo类的实例,并注入到容器中,一般这个类的名字使用AutoConfigure 结束,试验过其实也不一定。

    3.配置到 spring.factories 文件中。

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=
    com.example.demo.DemoAutoConfigure1

    4.在代码中使用Demo实例。

    @RestController
    public class DemoController {
    
        @Autowired
        private Demo demo;
    
        @GetMapping("/demo")
        public String demo(){
            return demo.hello();
        }
    }

    如果正常 这个实例是可用的。

    我们也可以在这个配置类上增加一些条件注解比如:

    @ConditionalOnJava(range = ConditionalOnJava.Range.EQUAL_OR_NEWER,value = JavaVersion.NINE)

    比如比如使用java的版本,我当前使用的是java8 ,执行后抛出错误如下:

    The injection point has the following annotations:
    	- @org.springframework.beans.factory.annotation.Autowired(required=true)
    
    The following candidates were found but could not be injected:
    	- Bean method 'demo' in 'DemoAutoConfigure1' not loaded because @ConditionalOnJava (9 or newer) found 1.8
  • 相关阅读:
    vb 使用Cystal Reports 9小例子
    VB Export sample
    c++文件結束符
    初学PHP:用post传递checkbox
    VB 图片在数据库的导入与导出
    vb 事务sample
    linux查找进程并杀掉进程
    WebRequest 对象的使用
    Asp操作Cookies(设置[赋值]、读取、删除[设置过期时间])
    .net webrequest应用
  • 原文地址:https://www.cnblogs.com/yg_zhang/p/12638261.html
Copyright © 2020-2023  润新知