Springboot加载动态Bean的10种方式

简介: Springboot加载动态Bean的10种方式
  1. 使用@Bean注解动态创建Bean

在Springboot中,可以使用@Bean注解在配置类中动态创建Bean,例如:

@Configuration
public class MyConfig {

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }

}
  1. 使用@Component注解动态创建Bean

除了使用@Bean注解创建Bean外,还可以使用@Component注解动态创建Bean,例如:

@Component
public class MyComponent {

    @Autowired
    private MyService myService;

    // ...

}
  1. 使用@Import注解动态导入Bean

使用@Import注解可以动态导入其他配置类中的Bean,例如:

@Configuration
@Import(MyConfig.class)
public class AppConfig {

    @Autowired
    private MyBean myBean;

    // ...

}
  1. 使用@ConfigurationProperties注解动态注入配置属性

使用@ConfigurationProperties注解可以动态注入配置属性,例如:

@Configuration
@ConfigurationProperties(prefix = "my.config")
public class MyConfig {

    private String name;

    private int age;

    // ...

}
  1. 使用@Value注解动态注入值

使用@Value注解可以动态注入值,例如:

@Component
public class MyComponent {

    @Value("${my.property}")
    private String myProperty;

    // ...

}
  1. 使用@Autowired注解动态注入Bean

使用@Autowired注解可以动态注入其他Bean,例如:

@Component
public class MyComponent {

    @Autowired
    private MyService myService;

    // ...

}
  1. 使用@Qualifier注解动态指定Bean

使用@Qualifier注解可以动态指定注入的Bean,例如:

@Component
public class MyComponent {

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

    // ...

}
  1. 使用@Lazy注解动态延迟加载Bean

使用@Lazy注解可以动态延迟加载Bean,例如:

@Component
@Lazy
public class MyComponent {

    @Autowired
    private MyService myService;

    // ...

}
  1. 使用FactoryBean动态创建Bean

使用FactoryBean可以动态创建Bean,例如:

public class MyFactoryBean implements FactoryBean<MyBean> {

    @Override
    public MyBean getObject() throws Exception {
        return new MyBean();
    }

    @Override
    public Class<?> getObjectType() {
        return MyBean.class;
    }

}
  1. 使用@Conditional注解动态创建Bean

使用@Conditional注解可以动态创建Bean,例如:

@Configuration
public class MyConfig {

    @Bean
    @Conditional(MyCondition.class)
    public MyBean myBean() {
        return new MyBean();
    }

}
目录
相关文章
|
27天前
|
Java 调度 Spring
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
44 0
|
1月前
|
XML Java 开发者
Spring Boot中的bean注入方式和原理
Spring Boot中的bean注入方式和原理
70 0
|
1月前
|
存储 NoSQL Java
Spring Boot统计一个Bean中方法的调用次数
Spring Boot统计一个Bean中方法的调用次数
35 1
|
20天前
|
安全 数据安全/隐私保护
Springboot+Spring security +jwt认证+动态授权
Springboot+Spring security +jwt认证+动态授权
|
9天前
|
Java Spring 容器
SpringBoot 使用Quartz执行定时任务对象时无法注入Bean问题
SpringBoot 使用Quartz执行定时任务对象时无法注入Bean问题
12 1
|
19天前
|
缓存 前端开发 Java
SpringBoot启动后加载初始化数据
SpringBoot启动后加载初始化数据
|
20天前
|
Java 测试技术 数据库
SpringBoot启动时设置不加载数据库
SpringBoot启动时设置不加载数据库
10 0
|
1月前
|
XML Java 数据格式
【springboot原理篇】Bean的加载方式,面试必看
【springboot原理篇】Bean的加载方式,面试必看
|
1月前
|
Java 容器 Spring
SpringBoot:Bean生命周期自定义初始化和销毁
SpringBoot:Bean生命周期自定义初始化和销毁
|
1月前
|
Java 开发者 容器
SpringBoot:详解Bean生命周期和作用域
SpringBoot:详解Bean生命周期和作用域