@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

猜你喜欢

转载自www.cnblogs.com/yg_zhang/p/12638261.html