为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Smart猫小萌 2019-03-06 13:15:20
<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=12、新建一个工具类ConstantsConfig来读取上面的.properties文件的常量。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的一些方法了。
查看完整描述

3 回答

?
梦里花落0921

TA贡献1772条经验 获得超6个赞

用属性配置文件可以解决

1、新增一属性文件,如config.propertiest,定义键值对dao.prefix=.

2、在spring配置文件中配置这个属性文件。

3、即可在<bean>中使属性文件的变量,如${dao.prefix}

4、在service中可以进行选择性注入:


<bean id='sysService' class='com.alan.***Impl>

    <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命名的规律性。


查看完整回答
反对 回复 2019-04-19
?
阿晨1998

TA贡献2037条经验 获得超6个赞

SystemUserServiceImpl implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    public void afterPropertiesSet() throws java.lang.Exception {

        if (***) {

            this.exm1 = applicationContext.getBean("exap1");

        } else {

            this.exm2 = applicationContext.getBean("exap2");

        }

    }


    public void setApplicationContext(ApplicationContext ctx) throws BeansException {

        this.applicationContext= ctx;

    }

}


查看完整回答
反对 回复 2019-04-19
  • 3 回答
  • 0 关注
  • 1662 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号