Trying to master Spring. I do everything on video Spring the Ripper , but nothing comes to the screen. Like the bean of the class InjectRandomIntAnnotationBeanPostProcessor simply ignored.
Please suggest what is the problem?
Bean itself:
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); } } Annotation:
@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 (actually where the text comes from):
public class Main { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("context.xml"); context.getBean(TerminatorQuoter.class).sayQuote(); }