RoboSpring。如何在项目中从库中扩展bean

时间:2014-12-10 15:14:53

标签: java android

我想在我的Android应用程序中使用RoboSpring作为控制反转。应用程序由Android库和单独的项目组成,它覆盖了库中的一些资源。还有很多其他项目使用这个库。所以库就像一个地下室,项目的作用是改变徽标,主题等,但不是应用程序的逻辑。但是现在我需要在其中一个应用程序中更改一些逻辑。所以我决定使用RoboSpring。

我是在库的src文件夹文件applicationContext.xml中用

创建的
<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/util
           http://www.springframework.org/schema/util/spring-util.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:annotation-config />

    <bean id="myServiceUrl" class="java.net.URL">
        <constructor-arg value="http://www.robospring.org" />
    </bean>

    <bean id="client" class="com.example.Client">
        <constructor-arg ref="clientParser"/>
    </bean>

    <bean id="clientParser" class="com.example.Parser"/>

</beans>

作为示例,我声明了一些bean,我需要在其中一个项目中更改clientParser。

问题#1:
我甚至无法覆盖项目中的文件applicationContext.xml,因为我会收到错误:Error generating final archive: Found duplicate file for APK: applicationContext.xml
我应该只在项目或内部库中保留applicationContext.xml,但是在每个项目中复制这个文件并不好。我认为它可以通过使用自定义contextConfigLocation解决,但不知道如何。

问题#2
即使我成功覆盖了context.xml,我怎么能只覆盖部分bean,实际上只有一个bean呢?因为我认为文件没有合并,我应该覆盖整个xml文件。

其实我是控制反转的新手,也许我选择了不正确的工具来解决我的问题,所以任何帮助都会受到赞赏

1 个答案:

答案 0 :(得分:1)

这是一个与Spring相关的问题,您可以使用RoboSpring解决它,就像使用Spring Framework一样。请看一下这个答案:

https://stackoverflow.com/a/11834159/1210793

我建议在库项目中使用另一个名称作为上下文定义,例如: 库context.xml中。您可以在每个相关项目的 applicationContext.xml 中导入它,如下所示:

<!-- import from the classpath of your library -->
<import resource="classpath:library-context.xml"/>

<!-- overriding the clientParser bean -->
<bean id="clientParser" class="another.Parser"/>

通过将Spring配置放在不同的源文件夹中,您也可以在使用Android的Build Variants(例如Product Flavors)时采用这种方法。

快乐超越!