Skip to content

Commit 9a1b0f4

Browse files
committed
Add InjectBeanPostProcessor.java
1 parent 2c0c5e2 commit 9a1b0f4

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package spring.oldboy.bean_post_processor;
2+
3+
/* Пример самописного пост-процессора с основным ...BeforeInitialization методом */
4+
5+
import org.springframework.beans.BeansException;
6+
import org.springframework.beans.factory.config.BeanPostProcessor;
7+
import org.springframework.context.ApplicationContext;
8+
import org.springframework.context.ApplicationContextAware;
9+
import org.springframework.stereotype.Component;
10+
import org.springframework.util.ReflectionUtils;
11+
12+
import java.util.Arrays;
13+
14+
@Component
15+
public class InjectBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {
16+
17+
private ApplicationContext applicationContext;
18+
19+
@Override
20+
public Object postProcessBeforeInitialization(Object bean, String beanName)
21+
throws BeansException {
22+
Arrays.stream(bean.getClass().getDeclaredFields())
23+
.filter(field -> field.isAnnotationPresent(InjectBean.class))
24+
.forEach(field -> {
25+
Object beanToInject = applicationContext.getBean("pool2",field.getType());
26+
ReflectionUtils.makeAccessible(field);
27+
ReflectionUtils.setField(field, bean, beanToInject);
28+
});
29+
30+
return bean;
31+
}
32+
33+
@Override
34+
public Object postProcessAfterInitialization(Object bean, String beanName)
35+
throws BeansException {
36+
return bean;
37+
}
38+
39+
@Override
40+
public void setApplicationContext(ApplicationContext applicationContext)
41+
throws BeansException {
42+
this.applicationContext = applicationContext;
43+
}
44+
45+
46+
}

0 commit comments

Comments
 (0)