首页后端开发JAVASpringboot加载动态Bean的10种方式(springboot 动态加载bean)

Springboot加载动态Bean的10种方式(springboot 动态加载bean)

时间2023-03-27 14:22:25发布访客分类JAVA浏览925
导读:使用@Bean注解动态创建Bean在Springboot中,可以使用@Bean注解在配置类中动态创建Bean,例如:@Configuration public class MyConfig { @Bean public M...
  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 FactoryBeanMyBean>
 {


    @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();

    }


}
    

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

java

若转载请注明出处: Springboot加载动态Bean的10种方式(springboot 动态加载bean)
本文地址: https://pptw.com/jishu/366.html
漫谈模式之行为模式小结(行为模式的概念) 学习研究Jrebel自建激活服务器 – 支持全部版本IDEA

游客 回复需填写必要信息