Java bean 动态注入记录---不求甚解,工作中可能需要根据配置有条件地创建一些bean

文章介绍了如何使用Spring的@ConditionalOnProperty注解,根据配置文件中的值动态注入不同实现的TestServicebean,以及自定义工具类和枚举来管理不同服务的实例。

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

工作业务需要,根据不同项目注入不同的bean 

1.@ConditionalOnProperty的功能
它主要是通过自身的两个属性来控制自动配置是否生效,这两个属性分别是name、havingValue。只有当配置文件(application.properties或者bootstrap.yml)中和name相同的属性的值和注解上havingValue的值相同时,该配置文件才会生效。

(该方式我用于与项目部地方平台对接时,根据不同地区注入不同bean去执行业务)


/**
 * 公共接口
 */
public interface TestService {
    void test();
}
/**
 * 测试实现1
 */
@Configuration
@ConditionalOnProperty(name = "test.testBean", havingValue = "test1")
public class Test1ServiceImpl implements TestService {
    @Override
    public void test() {
        System.out.println("Bean test1");
    }
}
/**
 * 测试实现2
 */
@Configuration
@ConditionalOnProperty(name = "test.testBean", havingValue = "test2")
public class Test2ServiceImpl implements TestService {
    @Override
    public void test() {
        System.out.println("Bean test2");
    }
}
//配置文件添加配置
// 对应注解 @ConditionalOnProperty(name = "test.testBean", havingValue = "test1")
test:
  testBean: test1

写个测试类

@SpringBootTest(classes = TestApplication.class)
@RunWith(SpringRunner.class)
public class TransferTest {

    @Autowired
    private TestService testService;

    @Test
    public void test() {
        testBean();
    }

    public void testBean() {
        testService.test();
    }
}

控制台输出:

2.org.springframework.beans.factory.config.BeanFactoryPostProcessor。 BeanFactory是Spring中容器功能的基础,用于存放所有已经加载的bean,

①.首先手写一个工具类,spring工具类,方便开发
/**
 * spring工具类 方便在非spring管理环境中获取bean
 */
@Component
public final class SpringUtils implements BeanFactoryPostProcessor {

    /**
     * Spring应用上下文环境
     */
    private static ConfigurableListableBeanFactory beanFactory;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringUtils.beanFactory = beanFactory;
    }

    /**
     * 获取对象
     *
     * @param name
     * @return Object 一个以所给名字注册的bean的实例
     * @throws BeansException
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) beanFactory.getBean(name);
    }

}

 ②枚举,记录对接方式

public class ServerModeEnumCons {

    @AllArgsConstructor
    @Getter
    public enum ServerEnum {

        WebService("webServiceTestService", "WebService"),
        REST("restTestService", "REST");

        private String label;
        private String value;



        public static ServerModeEnumCons.ServerEnum getEnumByValue(String value) {
            ServerModeEnumCons.ServerEnum.values();
            for (ServerModeEnumCons.ServerEnum serverMode : ServerModeEnumCons.ServerEnum.values()) {
                if (value.equals(serverMode.getValue())) {
                    return serverMode;
                }
            }
            return null;
        }
    }

}

③公共接口

public interface TestService {
    void test();
}

④多实现类


@Service("restTestService")
public class RestTestServiceImpl implements TestService {

    @Override
    public void test() {
        System.out.println("REST 方式调用成功");
    }
}
@Service("webServiceTestService")
public class WebServiceTestServiceImpl implements TestService {
    @Override
    public void test() {
        System.out.println("WebService 方式调用成功");
    }
}

⑤写个测试类

@SpringBootTest(classes = TestApplication.class)
@RunWith(SpringRunner.class)
public class TransferTest {


    @Test
    public void test() {
        testBean("WebService");
    }

    public void testBean(String type) {
        ServerModeEnumCons.ServerEnum enumByValue = ServerModeEnumCons.ServerEnum.getEnumByValue(type);
        TestService testService =SpringUtils.getBean(enumByValue.getLabel());
        testService.test();
    }
}

 ⑥运行一下控制台输出,

3.通过枚举单例

@Component
public class BeanFactoryUtils implements ApplicationContextAware {

    private static RestTestServiceImpl restTestServiceImpl ;
    private static WebServiceTestServiceImpl webServiceTestServiceImpl ;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        restTestServiceImpl = applicationContext.getBean(RestTestServiceImpl.class);
        webServiceTestServiceImpl = applicationContext.getBean(WebServiceTestServiceImpl.class);
    }

    @AllArgsConstructor
    @Getter
    public enum Type {

        WEBSERVICE("WEBSERVICE", webServiceTestServiceImpl  ),
        REST("REST", restTestServiceImpl );

        private String label;
        private TestService  testService ;

        public static TestService getBean(String label) {
            for (BeanFactoryUtils.Type type : BeanFactoryUtils.Type.values()) {
                if (label.equals(type .getLabel())) {
                    return type.getTestService();
                }
            }
            return null;
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值