3

Пишу приложение на java с использованием Spring. Нужно передать значение ключа из файла app.properties в поле класса. Передает null. Выскакивает NullPointerException, уже не знаю что и делать, помогите кто чем может

конфигурация spring:

<context:property-placeholder location="classpath:/app.properties"/>
<context:component-scan base-package="com"/>
<context:annotation-config/>
<mvc:annotation-driven />
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:app.properties"/>
</bean>

файл properties:

price=^[1-9][0-9.]{0,10}

в классе:

import org.springframework.beans.factory.annotation.Value;
....
@Value("${price}")
private String price;
private Pattern PRICE_REGEX = Pattern.compile(price);

2 ответа 2

4

@Value("${price}") в твоём случае работает. Другое дело, что ты вызываешь private Pattern PRICE_REGEX = Pattern.compile(price); до того, как отработает @Value. Тебе надо перенести логику инициализации PRICE_REGEX в post-конструктор. На выходе должно получиться примерно так:

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

@Component
public class Question909652 implements InitializingBean {

    @Value("${price}")
    private String price;
    private Pattern PRICE_REGEX;

    @Override
    public void afterPropertiesSet() throws Exception {
        PRICE_REGEX = Pattern.compile(price);
    }
}

Ну или можно похитрить и использовать всю мощь SpEL

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

@Component
public class Question909652 {

    @Value("#{T(java.util.regex.Pattern).compile('${price}')}")
    private Pattern PRICE_REGEX;

}

P.S. Как правильно заметил @Qwertiy, у тебя очень странное регулярное выражение для цены, быть может тебе больше подойдёт [0-9]*([.][0-9]{1,2})?

2
  • А ещё сам паттерн неправильный)
    – Qwertiy
    21 ноя 2018 в 16:36
  • Спасибо, работает))) 22 ноя 2018 в 8:15
0

Добавь аннотацию @PropertySource("classpath:app.properties").

1
  • к сожалению, та же ошибка( 21 ноя 2018 в 13:55

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.