gpt4 book ai didi

java - 如何在 Spring 单例 Controller 中注入(inject)原型(prototype) bean

转载 作者:太空宇宙 更新时间:2023-11-04 13:22:31 26 4
gpt4 key购买 nike

我有一个用于原型(prototype) bean 的 FactoryBean,如下所示:

@Component
public class ApplicationConfigurationMergedPropertiesFactoryBean implements SmartFactoryBean<Properties>{

@Autowired
protected ApplicationConfigurationInitializer initializer;

@Override
public Properties getObject() throws Exception {
return XXXXXXXXXX;
}

@Override
public Class<?> getObjectType() {
return Properties.class;
}

@Override
public boolean isSingleton() {
return false;
}

@Override
public boolean isPrototype() {
return true;
}

我想在 Controller 中 Autowiring 它,并且每当我尝试访问属性(通过p.get())时,都会从ApplicationConfigurationMergedPropertiesFactoryBean.getObject()获得一个新的原型(prototype)实例:

@Controller
@RequestMapping("/home")
public class HomeController {

@Autowired
@Qualifier("applicationConfig")
private Properties p;

@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public String home() {
System.out.println(p.get("something"));
}

但是这永远不会调用 getObject()。如果我注入(inject) ApplicationContext 并直接访问 bean,它就会起作用,提供一个全新的 Properties bean:

@Controller
@RequestMapping("/home")
public class HomeController {

@Autowired
@Qualifier("applicationConfig")
private Properties p;

@Autowired
private ApplicationContext ac;

@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public String home() {
System.out.println(p.get("something")); //WRONG!!!!
System.out.println(ac.getBean("applicationConfig", Properties.class).getProperty("something")); //OK!!!!

如何通过 @Autowired 注入(inject)直接实现这一点?

最佳答案

您是否考虑过让您的 Controller 类也具有原型(prototype)范围?

@Controller
@Scope("prototype")
@RequestMapping("/home")
public class HomeController {

关于java - 如何在 Spring 单例 Controller 中注入(inject)原型(prototype) bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32950508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com