我有以下情况
-具有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文件中读取值。附言我是Spring的新手,真的不知道该如何做
非常感谢您的帮助
最佳答案
我认为,您必须按如下所示向构造xml添加构造函数-arg。
<bean id="mongoService" class="com.business.persist.MongoService">
<constructor-arg type="java.lang.String">
<value>host</value>
</constructor-arg>
<constructor-arg type="int">
<value>port</value>
</constructor-arg>
<constructor-arg type="java.lang.String">
<value>database</value>
</constructor-arg>
</bean>
我不确定,最好的方法可能是添加基于Java的Bean配置。从xml中删除bean定义,并添加基于Java的congfig,如下所示
@Service
public class MongoService {
private final Mongo mongo;
private final String database;
private static final Logger LOGGER = LoggerFactory.getLogger(MongoService.class);
@bean
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;
}
}
高温超导