仅当 *.properties 文件中存在时才设置属性
setting properties only if present in *.properties file
我正在使用 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd ">
<bean id="aClassInstance" class="a.package.AClass">
<property name="prop1" value="${prop.1}" />
<property name="prop2" value="${prop.2}" />
</bean>
</beans>
我正在使用 PropertySourcesPlaceholderConfigurer
将 "${}"
占位符替换为 *.properties
文件中的值。我希望能够在 bean 中设置 属性 仅当 *.properties
文件中相应的 属性 存在时。这可能吗?
如果 属性 不存在,假设您需要默认值,那么您可以尝试类似的方法:
<bean id="aClassInstance" class="a.package.AClass">
<property name="prop1" value="${prop.1:default}" />
<property name="prop2" value="${prop.2:default}" />
</bean>
您可以在 PropertySourcesPlaceholderConfigurer
上将 ignoreUnresolvablePlaceholders
设置为 true
,当您尝试注入的 属性 在 [=13= 中丢失时,它不会引发异常] 文件。
PropertyOverrideConfigurer
允许您使用 beanName.property = value
语法设置属性。如果属性文件中不存在特定 属性,则 Spring 不会调用任何 setter。
因此,您可以使用 PropertySourcesPlaceholderConfigurer
替换构造函数中的占位符,并使用 PropertyOverrideConfigurer
设置可选属性。如果有不符合 beanName.property
语法的占位符,您可以使用 PropertyOverrideConfigurer.setIgnoreInvalidKeys(true)
。
我正在使用 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd ">
<bean id="aClassInstance" class="a.package.AClass">
<property name="prop1" value="${prop.1}" />
<property name="prop2" value="${prop.2}" />
</bean>
</beans>
我正在使用 PropertySourcesPlaceholderConfigurer
将 "${}"
占位符替换为 *.properties
文件中的值。我希望能够在 bean 中设置 属性 仅当 *.properties
文件中相应的 属性 存在时。这可能吗?
如果 属性 不存在,假设您需要默认值,那么您可以尝试类似的方法:
<bean id="aClassInstance" class="a.package.AClass">
<property name="prop1" value="${prop.1:default}" />
<property name="prop2" value="${prop.2:default}" />
</bean>
您可以在 PropertySourcesPlaceholderConfigurer
上将 ignoreUnresolvablePlaceholders
设置为 true
,当您尝试注入的 属性 在 [=13= 中丢失时,它不会引发异常] 文件。
PropertyOverrideConfigurer
允许您使用 beanName.property = value
语法设置属性。如果属性文件中不存在特定 属性,则 Spring 不会调用任何 setter。
因此,您可以使用 PropertySourcesPlaceholderConfigurer
替换构造函数中的占位符,并使用 PropertyOverrideConfigurer
设置可选属性。如果有不符合 beanName.property
语法的占位符,您可以使用 PropertyOverrideConfigurer.setIgnoreInvalidKeys(true)
。