Spring Boot 教程

@SpringBootConfiguration 注解

SpringBootConfiguration 是 SpringBoot 项目的配置注解,这也是一个组合注解,SpringBootConfiguration 注解可以用 java 代码的形式实现 Spring 中 xml 配置文件配置的效果,并会将当前类内声明的一个或多个以 @Bean 注解标记的方法的实例纳入到 spring 容器中,并且实例名就是方法名。

SpringBootConfiguration 可以作为 Spring 标准中 @Configuration 注解的替代。SpringBoot 项目中推荐使用@SpringBootConfiguration 替代 @Configuration。

为了进一步了解 SpringBootConfiguration 注解,查看一下它的源码:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
   @AliasFor(annotation = Configuration.class)
   boolean proxyBeanMethods() default true;
}

从源码上面可以得知,SpringBootConfiguration 注解上使用了 @Configuration 注解。因此 @SpringBootConfiguration 可以替代 @Configuration 注解。

proxyBeanMethods

该属性用来指定是否应该代理 @Bean 方法以强制执行 bean 生命周期行为。例如,即使在用户代码中直接调用 @Bean 方法的情况下,也返回共享的单例 bean 实例。此特性需要通过运行时生成的 CGLIB 子类实现方法拦截,该子类有一些限制,例如配置类及其方法不允许声明为 final。

默认为 true,它允许在配置类中进行 “bean间引用”,以及对该配置的 @Bean 方法的外部调用,例如从另一个配置类中调用。如果由于每个特定配置的 @Bean 方法都是自包含的并且被设计为供容器使用的普通工厂方法,则不需要这样做,请将此标志切换为 false,以避免处理 CGLIB 子类。

关闭 bean 方法拦截可以有效地单独处理 @Bean 方法,就像在非 @Configuration 上声明时那样。“@Bean Lite模式” 请参见 @Bean 注解的文档。因此,它的行为相当于删除 @Configuration 注解。

示例代码

(1)定义一个 Bean

public class MyBean {
    private String message;

    public MyBean(String message) {
        this.message = message;
    }
    // 忽略 getter 和 setter 方法
}

(2)使用 @SpringBootConfiguration 注解声明一个配置类,该类中配置了一个 Bean,该 Bean 的实例名称为 “getMyBean”。代码如下:

import com.huangx.springboot.springboot_springbootconfiguration_demo1.model.MyBean;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

@SpringBootConfiguration
public class MyConfig {

    @Bean
    public MyBean getMyBean() {
        return new MyBean("Hello! Spring Boot");
    }

}

(3)在 Spring Boot 的启动类中使用 “getMyBean” 名称获取 MyBean 的实例,然后在 index() 方法中调用。代码如下:

import com.huangx.springboot.springboot_springbootconfiguration_demo1.model.MyBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class Demo1Application {

    @Autowired
    @Qualifier("getMyBean")
    private MyBean myBean;

    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);
    }

    @RequestMapping("/")
    public String index() {
        return myBean.getMessage();
    }

}
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号