Spring Boot 动态注入的两种方式

本文介绍了Spring Boot中动态注入的两种方式:1) 利用@Profile结合spring.profiles.active,即使没有对应配置文件也能作为参数使用,常与@Component注解配合;2) 使用@Configuration配以@ConditionalOnProperty,根据配置文件中的特定值决定是否加载bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过@Profile+spring.profiles.active

spring.profiles.active:官方解释是激活不同环境下的配置文件,但是实际测试发现没有对应的配置文件也是可以正常执行的。那就可以把这个key当作一个参数来使用
@Profile:spring.profiles.active中激活某配置则在spring中托管这个bean,配合@Component,@Service、@Controller、@Repository等使用

@Component
@Profile("xx")
public class XxxTest extends BaseTest {
    public void test(){
        System.out.println("in XxxTest ");
    }
}
@Component
@Profile("yy")
public class YyyTest extends BaseTest {
    public void test(){
        System.out.println("in YyyTest ");
    }
}
 
@Service
public class MyService  {
 
 @Autowired
 private BaseTest  test;
 
    public void printConsole(){
        test.test();
    }
}
 
//配置文件激活某个环境则test就会注入哪个bean
spring.profiles.active=xx

通过@Configuration+@ConditionalOnProperty

@Configuration:相当于原有的spring.xml,用于配置spring
@ConditionalOnProperty:依据激活的配置文件中的某个值判断是否托管某个bean,org.springframework.boot.autoconfigure.condition包中包含很多种注解,可以视情况选择

@Configuration
public static class ContextConfig {
@Autowired
private XxxTest xxTest;
@Autowired
private YyyTest yyTest;
 
@Bean
@ConditionalOnProperty(value = "myTest",havingValue = "xx")
 public BaseTest  xxxTest() {
  return xxTest;
 }
 
 @Bean
@ConditionalOnProperty(value = "myTest",havingValue = "yy")
 public BaseTest yyyTest() {
  return yyTest;
 }
//配置文件中控制激活哪个bean
myTest=xx
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值