11

我有一个使用spring 3.0的web应用程序。我需要从使用appcontext xml中定义的bean的cron(使用组件扫描注释)中运行main方法。我有我的主要类在同一个src目录。 我怎样才能从Web上下文注入到主要方法的bean。我试图用在主要方法类中的春豆注入

ApplicationContext context = new ClassPathXmlApplicationContext("appservlet.xml"); 

我试过使用AutoWired,它返回一个空的bean。所以我使用了Application ctx,并且在运行main方法时创建了一个新的上下文(如预期的那样)。但是,我可以使用容器中的现有bean吗?

@Autowired 
static DAO dao; 

    public static void main(String[] args) { 
       ApplicationContext context = new ClassPathXmlApplicationContext("xman-   servlet.xml"); 
    TableClient client = context.getBean(TableClient.class); 
    client.start(context); 

} 
+1

对于未来的读者,一个密切相关的问题:http://stackoverflow.com/questions/3659720/spring-3-autowire-in-standalone-application – Jonik

回答

1

您可以为主应用程序使用spring上下文,并重用与webapp相同的bean。你甚至可以重用一些Spring XML配置文件,只要它们没有定义在webapp上下文中有意义的bean(请求范围,Web控制器等)。

但是你会得到不同的实例,因为你将有两个JVM运行。如果你真的想重复使用相同的bean实例,那么你的主类应该使用Web服务或HttpInvoker远程调用Web应用程序中的某种bean方法。

4

您不能将Spring bean注入到Spring未创建的任何对象中。另一种说法是:Spring只能注入到它管理的对象中。

由于您正在创建上下文,因此您需要为DAO对象调用getBean。

检查出Spring Batch它可能对您有用。

2

尝试用这个主:

public class Main { 

    public static void main(String[] args) { 
     Main p = new Main(); 
     p.start(args); 
    } 

    @Autowired 
    private MyBean myBean; 
    private void start(String[] args) { 
     ApplicationContext context = 
      new ClassPathXmlApplicationContext("classpath*:/META-INF/spring/applicationContext*.xml"); 
     System.out.println("The method of my Bean: " + myBean.getStr()); 
    } 
} 

这豆:

@Service 
public class MyBean { 
    public String getStr() { 
     return "mybean!"; 
    } 
} 
1

春季启动此提供了一个官方的解决方案。从

https://start.spring.io/

下载的骨架,并在pom.xml确保包装设置为罐子。只要您不包含任何Web依赖项,应用程序将保持为控制台应用程序。