简体   繁体   English

Spring:如何通过读取外部属性文件来使用@Value注释注入值?

[英]Spring: How to inject values with @Value annotation by reading from external properties file?

I have following situation 我有以下情况
- Have a MongoService class, which reads host, port, database from file - 有一个MongoService类,它从文件中读取主机,端口和数据库

xml configuration 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>  

The local.properties looks like local.properties看起来像

### === MongoDB interaction === ###
host="127.0.0.1"
port=27017
database=contract

and MongoService Class as 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;
    }
}

When I want to test that bean is fine, I do the following in 当我想测试豆子没问题的时候,我会做以下几点
MongoServiceTest.java MongoServiceTest.java

public class MongoServiceTest {

    @Autowired
    private MongoService mongoService;

}

It complains saying that can not identify bean for MongoService . 它抱怨说can not identify bean for MongoService

Then I add the following to above xml 然后我将以下内容添加到上面的xml中

<bean id="mongoService" class="com.business.persist.MongoService"></bean>

Then it complains saying "No Matching Constructor found" 然后它抱怨说"No Matching Constructor found"

What I want to do 我想做的事

a.) MongoService should be @Autowired and reads configuration params from <value>file:///storage/local.properties</value> a。)MongoService应该是@Autowired并从<value>file:///storage/local.properties</value>读取配置参数

Question

a.) Is accessing values in constructor are correct? a。)在构造函数中访问值是否正确? (file name is local.properties and I am using @Value("#{ systemProperties['host']}") syntax)

b.) What is that I need to make it work so that @Autowired private MongoService mongoService loads correctly and reads value off local.properties file. b。)我需要做什么才能使@Autowired private MongoService mongoService正确加载并从local.properties文件中读取值。

PS I am very new to Spring and don't really know how to make this work PS我是Spring的新手,并不知道如何使这项工作

Thanks much for your help in advance 非常感谢您的帮助

I think , You have to add constructor-arg to config xml as follows. 我想,您必须将constructor-arg添加到config xml,如下所示。

<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>

I am not sure,Bst way could be adding java based bean config. 我不确定,Bst方式可以添加基于java的bean配置。 Remove the bean definition from xml and add java-based congfig as follows 从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;
    }
}

HTH HTH

By default, Spring instantiates objects using the default constructor (with no args) and then uses the setter methods to set all the properies. 默认情况下,Spring使用默认构造函数(没有args)实例化对象,然后使用setter方法设置所有属性。 If you don't want to (or can't) use the setters or define a default construtor, you have to tell spring what to pass in as constructor args. 如果你不想(或不能)使用setter或定义默认的construtor,你必须告诉spring传入什么作为构造函数args。

Here is a blog post explaining how it can be done: 这是一篇博客文章,解释了如何完成它:
http://www.javalobby.org/java/forums/t18396.html http://www.javalobby.org/java/forums/t18396.html

The basic syntax looks like this: 基本语法如下所示:

<bean name="MyBean" class="com.example.BeanClass">
  <constructor-arg index="0"><ref bean="OtherBeanName"/></constructor-arg>
</bean>

The index attribute is optional but it requires you to order the XML constructor-arg elements in the same order as the params to the constructor. index属性是可选的,但它要求您按照与constructor-arg的params相同的顺序对XML constructor-arg元素进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring:使用@Value注释时,Bean无法从外部属性文件中读取值 - Spring: Bean fails to read off values from external Properties file when using @Value annotation 从属性文件中读取列表并加载弹簧注释 @Value - Reading a List from properties file and load with spring annotation @Value 从属性文件中读取Map并使用spring注释加载@Value - Reading a Map from properties file and load with spring annotation @Value Spring 来自外部文件的引导注入属性 - Spring Boot inject properties from external file 如何在Spring上下文中注入外部属性文件 - How to Inject an external properties file in spring context 如何使用@Named批注从Spring 3.0的属性中注入构造函数参数? - How to inject constructor parameters from properties in Spring 3.0 with the @Named annotation? @Value Annotation不从属性文件中注入值 - @Value Annotation not injecting values from properties file 使用注释弹簧4在jsp中读取属性文件 - reading properties file in jsp using annotation spring 4 如何使用Spring注释将Properties文件中的值注入到现有实例(不受Spring管理)的字段中? - How do I inject a value from Properties file to a field of an existing instance (not managed by Spring) using Spring annotations? 从属性文件中读取TestNG批注参数值 - Reading TestNG annotation parameter value from Properties file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM