我有问候豆:
@Component
public class Greeting implements IGreeting {
private String greeting;
// setter and getter
}
我有BeanFactoryPostProcessor
:
@Component
public class GreetingBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
BeanDefinition beanDefinition = configurableListableBeanFactory.getBeanDefinition("greeting");
beanDefinition.setFactoryBeanName("greetingBeanFactory");
}
}
我有BeanFactory
:
@Component
public class GreetingBeanFactory extends AbstractFactoryBean<Object> {
@Override
public Class<Greeting> getObjectType() {
return Greeting.class;
}
@Override
protected Object createInstance() throws Exception {
LocalDateTime currentTime = LocalDateTime.now();
int hour = currentTime.getHour();
IGreeting greeting = new Greeting();
if ((hour >= 7) && (12 > hour)) {
greeting.setGreeting("morning");
}else if((hour >= 12) && (18 > hour)) {
greeting.setGreeting("day");
}else if((hour >= 18) && (24 > hour)){
greeting.setGreeting("evening");
}else if((hour >= 0) && (7 > hour)){
greeting.setGreeting("night");
}
System.out.println("Tuned 'Greeting' by Factory Bean: " + greeting);
return greeting;
}
}
和控制器:
@RestController
public class HelloController {
@Autowired
IGreeting greeting;
@RequestMapping("/hello_world")
public String index() {
System.out.println("Actual `Greeting` used in application: " + greeting);
return String.format("Good %s!", greeting.getGreeting());
}
}
我正在记录实例并看到以下内容:
Tuned 'Greeting' by Factory Bean: com.epam.springboot.model.Greeting@514eedd8
Actual `Greeting` used in application: com.epam.springboot.model.Greeting@39c4a65a
为什么我的FactoryBean
实例调整失败了,为什么我会得到一个新实例
在控制器?是否可以使用架构,它是FactoryBean
和FactoryBeanPostProcessor
用法的好例子吗?