我有以下情况
- 有一个 MongoService 类,它从文件中读取主机、端口、数据库
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"
我想做的事
a.) MongoService 应该是@Autowired
并从中读取配置参数<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 文件中读取值。
PS我对Spring很陌生,真的不知道如何使这项工作
非常感谢您提前提供的帮助