我有以下情況
- 有一個MongoService類,它從文件中讀取主機,端口,數據庫Spring:如何使用@Value註釋從外部屬性文件讀取注入值?
xml配置
<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-3.0.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:///storage/local.properties</value>
</list>
</property>
</bean>
</beans>
的local.properties看起來像
### === MongoDB interaction === ###
host="127.0.0.1"
port=27017
database=contract
和MongoService類別作爲
@Service
public class MongoService {
private final Mongo mongo;
private final String database;
private static final Logger LOGGER = LoggerFactory.getLogger(MongoService.class);
public MongoService(@Nonnull final @Value("#{ systemProperties['host']}") String host, @Nonnull final @Value("#{ systemProperties['port']}") int port, @Nonnull final @Value("#{ systemProperties['database']}") String db) throws UnknownHostException {
LOGGER.info("host=" + host + ", port=" + port + ", database=" + db);
mongo = new Mongo(host, port);
database = db;
}
}
當我想測試bean是很好,我做的在
MongoServiceTest.java
public class MongoServiceTest {
@Autowired
private MongoService mongoService;
}
下它抱怨說,can not identify bean for MongoService
。
然後我以下內容添加到上面的XML
<bean id="mongoService" class="com.business.persist.MongoService"></bean>
然後它抱怨說"No Matching Constructor found"
我想做
一)MongoService應@Autowired
什麼和讀取配置PARAMS來自<value>file:///storage/local.properties</value>
問題
a。)訪問構造函數中的值是否正確? (file name is local.properties and I am using @Value("#{ systemProperties['host']}") syntax)
b)什麼是我需要使它工作,以便@Autowired private MongoService mongoService
正確加載並從local.properties文件讀取值。
P.S.我很新的春天和真的不知道如何使這項工作
感謝很多的幫助提前
我不覺得@Bean – daydreamer
http://static.springsource.org/spring-javaconfig/docs/1.0 .0.M4/reference/html/ch02s02.html – nayakam
我收到錯誤,提示'@Bean無法應用於構造函數 – daydreamer