如何提供当前BeanFactory作为构造函数参数

时间:2011-04-05 18:09:02

标签: java spring

我有一个单例类,我想用Spring的IoC创建。此类还需要使用IoC实例化动态数量的其他对象。因此,此类需要将BeanFactory作为构造函数参数传入。我怎么能这样做?

这是我计划的一般结构。我是Spring IoC的新手,所以如果它不适合Spring,我也愿意改变这个结构。

public class Main
{
    public static void main(String[] args)
    {
        ApplicationContext context =
                new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});

        MySingletonInterface instance = context.getBean(MySingletonInterface.class);

        instance.foo();
    }
}

public class MySingletonClass implements MySingletonInterface
{
    public MySingletonClass(BeanFactory beanFactory)
    {
        this.beanFactory = beanFactory;
    }

    public void foo()
    {
        for( ..... )
        {
            NeedManyInstances instance = beanFactory.getBean(NeedManyInstances.class);
            ....
        }
    }
}

1 个答案:

答案 0 :(得分:2)

最简单的方法是将构造函数声明为@Autowired(确保应用程序上下文is configured for use of annotation-based configuration<context:annotation-config/>):

@Autowired
public MySingletonClass(BeanFactory beanFactory) { ... }

另一种选择是让您的类实现BeanFactoryAware并使用setBeanFactory()方法而不是构造函数。