如何在Spring单例控制器中注入原型bean

时间:2015-10-05 14:01:36

标签: java spring spring-mvc dependency-injection

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

我想在控制器中自动装配它,每当我尝试访问属性时(通过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直接访问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注射直接实现这一目标?

2 个答案:

答案 0 :(得分: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()); 
   ....
   }

答案 1 :(得分:0)

您是否考虑过将控制器类作为原型范围?

string