autowire如何用于使用弹簧的方法?

时间:2013-12-05 17:18:22

标签: java spring

我有一个弹簧应用程序,现在需要为下面提到的方案提供一些建议。

我在调度程序中有一个方法,并且每次调度程序运行时我想在方法中创建一个新的bean对象,如下面的worker对象代码所示。那我怎么能实现这个呢?

while(itr.hasNext()){
        Device dev = itr.next();
        connDetails = new ConnectionDetails(dev.getIpaddress(), dev.getPort(), dev.getPassword(), dev.getPassword());

        ScheduledMessage worker = ?;
        worker.set_id(dev.get_id());
        worker.setConnDetails(connDetails);
        executor.execute(worker);
    }

2 个答案:

答案 0 :(得分:0)

在SpringConfig.xml中:

<!-- Enable the annotation usage (bean injection for instance) -->
<context:annotation-config />
<!-- Message bean (several instances) -->
<bean id="scheduledMessageBean" class="com.myapp.ScheduledMessage" scope="prototype" />

在你的java类中:

ScheduledMessage worker = BasicBeanFactory.getInstance().getBean("scheduledMessageBean");

您可以查看§3.2.1如何为您的应用程序构建BeanFactory(需要Spring Application上下文):http://docs.spring.io/spring/docs/1.2.9/reference/beans.html

例如(未经测试的例子):

public class BasicBeanFactory
{
    private static BasicBeanFactory instance = null;

    /** The application context. */
    private ApplicationContext ctx = null;

    protected BasicBeanFactory() {
        // Init spring context
        ctx = new ClassPathXmlApplicationContext("SpringConfig.xml");
    }

    public Object getBean(String name) throws BeanInstantiationException {
        Object bean = null;
        try {
            bean = ctx.getBean(name);
         } catch (BeansException e) {
            throw new BeanInstantiationException(e);
        }
        return bean;
    }

    public static BasicBeanFactory getInstance() {
        if (instance  == null) {
            instance= new BasicBeanFactory();
        }
        return instance;
    }

}

答案 1 :(得分:0)

从当前Spring上下文获取对象,该对象效果很好!