spring配置文件如何实现判断语句

<bean id="systemUserService" class="com.alan.SystemUserServiceImpl">

        <if ***>

            <property name="exm1" ref="exm1"></property>

        </if>

        <else if ***>

         <property name="exm2" ref="exm2"></property>

        </else if>

        <else>

        <property name="exm3" ref="exm3"></property>

        </else>

        

</bean>

不知道有spring的配置文件有没有以上的实现,根据判断条件来决定注入哪一个对象

++++++++++++++++++++++++++分隔线+++++++++++++++++++++++++++++++++


我所想到的另一途径是

1、新建一个.properties文件,来定义常量,如dubboOrSql=1

2、新建一个工具类ConstantsConfig来读取上面的.properties文件的常量。

https://img.mukewang.com/5cb962d60001721208000484.jpg

3、在serviceImpl类中,对此进行判断 ,来决定实例化哪个对象.


ISystemData sd;

String dubboOrSql = ConstantsConfig.getDubboOrSql();

if("1".equals(dubboOrSql)){

    sd = app.getBean("exap1");

}else if("0".equals(dubboOrSql)){

    sd = app.getBean("exap2");

}


//后面就是调用sd的一些方法了。


Smart猫小萌
浏览 1663回答 3
3回答

梦里花落0921

用属性配置文件可以解决1、新增一属性文件,如config.propertiest,定义键值对dao.prefix=.2、在spring配置文件中配置这个属性文件。3、即可在<bean>中使属性文件的变量,如${dao.prefix}4、在service中可以进行选择性注入:<bean id='sysService' class='com.alan.***Impl>&nbsp; &nbsp; <property name='***' ref='system${dao.prefix}Dao'></bean><bean id='systemDao' class='***'/><bean id='systemDubboDao class='***'/><bean id='systemOtherDao class='***'/>这样配置的话,就会根据dao.prefix的值来决定注入哪一个DAO了。当dao.prefix=null(即什么都不填是),ref='systemDao'。关键在于bean命名的规律性。

阿晨1998

SystemUserServiceImpl implements InitializingBean, ApplicationContextAware {&nbsp; &nbsp; private ApplicationContext applicationContext;&nbsp; &nbsp; public void afterPropertiesSet() throws java.lang.Exception {&nbsp; &nbsp; &nbsp; &nbsp; if (***) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.exm1 = applicationContext.getBean("exap1");&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.exm2 = applicationContext.getBean("exap2");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public void setApplicationContext(ApplicationContext ctx) throws BeansException {&nbsp; &nbsp; &nbsp; &nbsp; this.applicationContext= ctx;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java