4

Пытаюсь освоить Spring. Делаю все по видео Spring Потрошитель, но на экран ничего не выходит. Вроде бин класса InjectRandomIntAnnotationBeanPostProcessor просто игнорируется.

Просьба подсказать в чем проблема?

Сам бин:

public class TerminatorQuoter implements Quoter {
private String message;

@InjectRandomInt(min = 2, max = 7)
private int repeat;

public void setMessage(String message) {
    this.message = message;
}

public void sayQuote() {
    for (int i = 0; i < repeat; i++) {
        System.out.println("message = s" + message);
    }
}

Аннотация:

@Retention(RetentionPolicy.RUNTIME)
public @interface InjectRandomInt {
int min();
int max();
}

BeanPostProcessor:

public class InjectRandomIntAnnotationBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    Field[] fields = bean.getClass().getFields();
    for (Field field : fields) {
        InjectRandomInt injectRandomInt = field.getAnnotation(InjectRandomInt.class);
        if (injectRandomInt != null){
            int min = injectRandomInt.min();
            int max = injectRandomInt.max();
            Random random = new Random();
            int randomInt = min + random.nextInt(max - min);
            field.setAccessible(true);
            ReflectionUtils.setField(field, bean, randomInt);
        }
    }
    return bean;
}

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    return bean;
}

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.xsd">

<bean class="quoters.InjectRandomIntAnnotationBeanPostProcessor"/>
<bean class="quoters.TerminatorQuoter" id="terminatorQuoter">
    <property name="message" value="I'll be back!!!"/>
</bean>

Main.java (собственно откуда текст и не выходит):

public class Main {

public static void main(String[] args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
    context.getBean(TerminatorQuoter.class).sayQuote();
}
7
  • ошибки есть хоть какие? 1 ноя 2018 в 7:56
  • Нет, просто пустой экран (Process finished with exit code 0). IDE intellij idea может там куда посмотреть?
    – Vadim
    1 ноя 2018 в 7:57
  • IDE intellij idea - самый продвинутый, ошибка явно в коде 1 ноя 2018 в 8:00
  • попробуйте добавить getter & setter 1 ноя 2018 в 8:00
  • а код откуда брали? или сами? 1 ноя 2018 в 8:01

1 ответ 1

5

Вызов bean.getClass().getFields(); возвращает лишь public поля. Замените этот вызов на bean.getClass().getDeclaredFields();.

4
  • Помогло, спасибо! Еще вопрос, а можно ли обойтись без " ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("context.xml"); context.getBean(TerminatorQuoter.class).sayQuote(); "? Например в Servletах, как указать что используется context.xml?
    – Vadim
    1 ноя 2018 в 8:09
  • @Vadim если ответ решил вашу проблему, то вам стоит принять его, нажав галочку рядом с ним. 1 ноя 2018 в 8:11
  • ОК, сделал, спасибо за комментарии.
    – Vadim
    1 ноя 2018 в 8:12
  • @Vadim Можно: baeldung.com/spring-web-contexts 1 ноя 2018 в 8:51

Ваш ответ

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

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