2015-10-05 74 views
1

我有这样的原型豆类一个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; 
    } 

我想自动装配它的控制器和,每当我试图访问属性(通过p.get(),具有ApplicationConfigurationMergedPropertiesFactoryBean.getObject()一个新的原型实例:)

@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(如果我的豆直接注入的ApplicationContext的访问,它的工作原理,提供了一个全新的属性豆:

@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注入来实现?

+0

你不能只是注入ApplicationConfigurationMergedPropertiesFactoryBean吗? – WeMakeSoftware

+0

可能的重复:http://stackoverflow.com/questions/7621920/scopeprototype-bean-scope-not-creating-new-bean –

回答

0

你有没有考虑过让你的控制器类原型作用域呢?

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

我宁愿它是一个单例,我也不需要一个新的控制器实例对于每一个请求... – codependent

+0

得到亚,是啊这是我知道你可以完成你想要的东西,而无需明确地调用你的工厂的每一个请求的唯一途径。我曾经觉得不需要为每个请求创建控制器,但是如果它实现了你想要的行为,并且让Spring处理你不需要的东西想要明确。您可能会发现,如果您每次测量创建控制器的性能时都会增加可忽略的开销。 – Nate

0

注入厂家直接:

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

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

    @Autowired 
    private ApplicationContext ac; 

    @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) 
    public String home() { 
     System.out.println(p.getObject()); 
    .... 
    } 
+0

是的,这是一个解决方案。我想知道是否有比直接调用工厂更少的手工操作。就像你有一个@Scoped(“会话”或“请求”)bean,它会在控制器中为每个请求自动刷新一次 – codependent