最近采用公司的基于dubbo开发的分布式框架,组件通过jar包方式部署,只能读取src/main/java目录下的文件,无法读取src/main/resources下的文件。配置文件可以通过前端配置的方式写入到应用中去,但是框架自身只提供了配置数据库,redis以及spring等一些常见的配置的写入。
这里分开说明两种情况,举例说明,模板引擎需要提供模板文件,如freemaker,那么模板文件可以放在java类同级目录下存放,在配置org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer的时候配置属性
-
设置bean属性的方式set到bean中,构造函数的注入方式也是一样的道理
1 2 3 4 5 6 7 8 9 10 11
<bean id="myObsClientConfig" class="com.xxxx.ClientConfig"> <property name="accessId" value="xxxx" /> <property name="securityId" value="xxxx" /> </bean> <bean id="xxx" class="xxxxxx"> <constructor-arg index="0" value="红旗CA72"/> <constructor-arg index="1" value="中国一汽"/> <constructor-arg index="2" value="2666"/> </bean>
-
通过@value注解的方式注入
1.创建.properties文件:
在如下目录创建 keyvalue.properties 文件 src/main/java/xx/keyvalue.properties ,写入如下内容:
test.value=iloveyou
2.配置文件中将.properties文件引入:
在spring配置文件中加入如下内容:
1
2
3
4
5
6
7
8
9
10
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath*:META-INF/spring/*.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties"/>
</bean>
这里需要注意的是两个
3.使用@Value注解:引入Value 类,在需要取值的属性上方加上 @Value 注解,其中注明的 configProperties 和第一个
1
2
3
4
5
import org.springframework.beans.factory.annotation.Value;
@Value("#{configProperties['test.value']}")
private String testValue;
System.out.println("TestValue Is: " + testValue);
// 输出结果 Test Value Is: iloveyou