spring_Spring Boot中的@SpringBootConfiguration注释

spring

spring

Spring Boot中@SpringBootConfiguration注释是一个类级别的注释,它指示此类提供了应用程序配置。

通常,具有main()方法的类最适合此注释。

我们通常使用@SpringBootApplication批注,该批注会自动继承@SpringBootConfiguration批注。

注释用法:

当我们使用@SpringBootConfiguration标记一个类时,这意味着该类提供了@Bean定义方法。 Spring容器处理配置类以为我们的应用实例化和配置bean。

让我们看一下这个注释的用法示例:

@SpringBootConfiguration
public class DemoApp {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApp.class, args);
    }
 
    @Bean
    public Course course() {
        return new Course();
    }
 
    @Bean
    public Student student() {
        return new Student();
    }
}

根据Spring文档, @ SpringBootConfiguration只是Spring标准@Configuration批注的替代方法。 两者之间的唯一区别是@SpringBootConfiguration允许自动找到配置。

这在编写测试时特别有用。

如前所述, @SpringBootApplication批注包括@SpringBootConfiguration批注:

@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters={@ComponentScan.Filter(type
  =CUSTOM,classes=TypeExcludeFilter.class)})
public @interface <span class="memberNameLabel">SpringBootApplication</span>

我们最通常只使用@SpringBootApplication ,后者又包含了另一个。

请注意,建议在我们的应用程序中仅使用一个@SpringBootConfiguration@SpringBootApplication批注。

在为我们的Spring Boot应用程序编写测试用例时,我们遇到的常见异常之一是:

Unable to find a @SpringBootConfiguration, 
you need to use @ContextConfiguration or @SpringBootTest(classes=...)
 with your test java.lang.IllegalStateException

造成这种情况的主要原因通常是, @ DataJpaTest之类的测试注释以及其他一些注释首先在当前包中查找@SpringBootConfiguration注释。 万一它在当前包中丢失了,他们开始查找包层次结构,直到找到此注释。

确保您的测试类与使用@SpringBootApplication标记的类位于同一包中,或者至少位于包层次结构中较低的类中:

sample-app
  +--pom.xml
  +--src
    +--main
      +--com
        +--programmergirl
          +--Application.java
    +--test
      +--com
        +--programmergirl
          +--test
            +--SampleJpaTest.java

这样可以解决此问题。

结论:

在这个迷你教程中,我们讨论了@SpringBootConfiguration批注。 我们还看到,@SpringBootApplication包括对@SpringBootConfiguration的定义。

并且,我们将标准的Spring @Configuration@SpringBootConfiguration进行了比较

我们还有另一篇关于Spring核心注释的文章,可以帮助您学习Spring应用程序中使用的一些常见注释。 如果您愿意,请随时进行探索。

翻译自: https://www.javacodegeeks.com/2019/09/springbootconfiguration-annotation-spring-boot.html

spring

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值