Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring bean injection in a main method class

I have a web application with spring 3.0. I need to run a class with main method from a cron that uses beans defined in appcontext xml(using component scan annocations). I have my main class in same src directory. How can I inject beans from web context into main method. I tried to do it using

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

I tried to use AutoWired and it returns a null bean. So I used Application ctx and this is creating a new context (as expected) when I run main method. But is it possible that I can use existing beans from container.

 @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);

}
like image 783
riamob Avatar asked Nov 29 '11 15:11

riamob


3 Answers

Try with this Main:

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());
    }
}

And this Bean:

@Service 
public class MyBean {
    public String getStr() {
        return "mybean!";
    }
}
like image 139
madx Avatar answered Nov 01 '22 13:11

madx


You can not inject a Spring bean into any object that was not created by spring. Another way to say that is: Spring can only inject into objects that it manages.

Since you are creating the context, you will need to call getBean for your DAO object.

Check out Spring Batch it may be useful to you.

like image 6
DwB Avatar answered Nov 01 '22 13:11

DwB


You may use a spring context for your main application, and reuse the same beans as the webapp. You could even reuse some Spring XML configuration files, provided they don't define beans which only make sense in a webapp context (request-scope, web controllers, etc.).

But you'll get different instances, since you'll have two JVMs running. If you really want to reuse the same bean instances, then your main class should remotely call some method of a bean in your webapp, using a web service, or HttpInvoker.

like image 1
JB Nizet Avatar answered Nov 01 '22 14:11

JB Nizet