当前位置: 首页 > 面试题库 >

使用Spring配置文件设置系统属性

蒙墨竹
2023-03-14
问题内容

配置
Spring 2.5,Junit 4,Log4j
从系统属性中指定log4j文件位置

${log.location}

在运行时,使用-D java选项设置系统属性。一切都很好。

问题/我需要什么:
在单元测试时,未设置系统属性,并且文件位置未解析
App使用Spring,想简单地配置Spring以 设置 系统属性。

更多信息:
要求仅用于配置。无法引入新的Java代码或IDE中的条目。理想情况下,Spring的一种属性配置实现可以解决这个问题-我只是找不到合适的组合。

这个想法很接近,但是需要添加Java代码:
Spring
SystemPropertyInitializingBean

有什么帮助吗?任何想法表示赞赏。


问题答案:

您可以结合使用两个MethodInvokingFactoryBeans来实现

创建一个访问System.getProperties的内部bean,并在内部bean所获取的属性上调用putAll的外部bean:

<bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property
        name="targetObject">
        <!-- System.getProperties() -->
        <bean
            class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
            <property name="targetClass" value="java.lang.System" />
            <property name="targetMethod" value="getProperties" />
        </bean>
    </property>
    <property
        name="targetMethod"
        value="putAll" />
    <property
        name="arguments">
        <!-- The new Properties -->
        <util:properties>
            <prop
                key="my.key">myvalue</prop>
            <prop
                key="my.key2">myvalue2</prop>
            <prop
                key="my.key3">myvalue3</prop>

        </util:properties>
    </property>
</bean>

(当然,您可以只使用一个bean并以System.setProperties()为目标,但是随后您将替换现有属性,这不是一个好主意。

无论如何,这是我的小测试方法:

public static void main(final String[] args) {

    new ClassPathXmlApplicationContext("classpath:beans.xml");

    System.out.println("my.key: "+System.getProperty("my.key"));
    System.out.println("my.key2: "+System.getProperty("my.key2"));
    System.out.println("my.key3: "+System.getProperty("my.key3"));

    // to test that we're not overwriting existing properties
    System.out.println("java.io.tmpdir: "+System.getProperty("java.io.tmpdir"));
}

这是输出:

my.key: myvalue
my.key2: myvalue2
my.key3: myvalue3
java.io.tmpdir: C:\DOKUME~1\SEANFL~1\LOKALE~1\Temp\


 类似资料:
  • 我想根据环境变量设置Spring的活动配置文件。为此,我编写了以下代码: 这段代码被执行,但是,没有配置文件被设置为Spring writes:INFO-没有活动的配置文件集,返回到默认配置文件:default 我如何实现我想要的?

  • cmf_set_option($key, $data, $replace = false) 功能 设置系统配置,通用 参数 $key: string 配置键值,都小写 $data: array 配置值,数组 $replace: array 是否完全替换 返回 bool 是否成功

  • X2.2.0新增 sp_set_option($key,$data) 功能: 设置系统配置,通用 参数: $key: 配置的键名,英文下划线小写,最好加上自己的应用或插件名作为前级 $data:配置的值,数组 返回: 类型boolean,true设置成功 使用: $result = sp_set_option('portal_custom_settings',array('test'=>1));

  • 1.1. 文件系统配置 2. define CONFIG_EXTRA_ENV_SETTINGS \ 1.1. 文件系统配置 Rootfs文件系统设置成ubifs readonly,相应mount命令在uboot中设置,如下: $(K18DIR)/uboot/include/configs/leo_common.h / Extra Environment / … "mtdargs=ubi.mtd="

  • cmf_set_option($key, $data, $replace = false) 功能 设置系统配置,通用 参数 $key: string 配置键值,都小写 $data: array 配置值,数组 $replace: array 是否完全替换 返回 bool 是否成功

  • 您好,我最近在spring项目中将日志记录从log4j迁移到了log4j2。 一切正常,但我想知道如何设置属性