Using Spring 3 autowire in a standalone Java application

standalone java application using spring boot
how to autowire parameterized constructor in spring boot
spring load application context programmatically
spring boot autowire in main class
spring @autowired annotation example without xml
how to autowire interface in spring
spring dependency injection standalone
default autowiring in spring

Here is my code:

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("META-INF/config.xml");
        System.out.println("my beans method: " + myBean.getStr());
    }
}

@Service 
public class MyBean {
    public String getStr() {
        return "string";
    }
}

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
    <context:annotation-config /> 
    <context:component-scan base-package="mypackage"/>
</beans>

Why doesn't this work? I get NullPointerException. Is it possible to use autowiring in a standalone application?

Spring works in standalone application. You are using the wrong way to create a spring bean. The correct way to do it like this:

@Component
public class Main {

    public static void main(String[] args) {
        ApplicationContext context = 
            new ClassPathXmlApplicationContext("META-INF/config.xml");

        Main p = context.getBean(Main.class);
        p.start(args);
    }

    @Autowired
    private MyBean myBean;
    private void start(String[] args) {
        System.out.println("my beans method: " + myBean.getStr());
    }
}

@Service 
public class MyBean {
    public String getStr() {
        return "string";
    }
}

In the first case (the one in the question), you are creating the object by yourself, rather than getting it from the Spring context. So Spring does not get a chance to Autowire the dependencies (which causes the NullPointerException).

In the second case (the one in this answer), you get the bean from the Spring context and hence it is Spring managed and Spring takes care of autowiring.

Combining standalone application with Spring – Andi's Blog, When you are developing a standalone application, that you want to use with the Use of a factory class that can be used to initialize the no-bean class; Using aspects to resolve the autowiring 3. 4. 5. 6. private ComponentConsumer consumer; // <== Spring main class eclipse (18); Java (81). Home » Java » Using Spring 3 autowire in a standalone Java application. Using Spring 3 autowire in a standalone Java application . Posted by: admin October 21,

Spring is moving away from XML files and uses annotations heavily. The following example is a simple standalone Spring application which uses annotation instead of XML files.

package com.zetcode.bean;

import org.springframework.stereotype.Component;

@Component
public class Message {

   private String message = "Hello there!";

   public void setMessage(String message){

      this.message  = message;
   }

   public String getMessage(){

      return message;
   }
}

This is a simple bean. It is decorated with the @Component annotation for auto-detection by Spring container.

package com.zetcode.main;

import com.zetcode.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.zetcode")
public class Application {

    public static void main(String[] args) {

        ApplicationContext context
                = new AnnotationConfigApplicationContext(Application.class);

        Application p = context.getBean(Application.class);
        p.start();
    }

    @Autowired
    private Message message;
    private void start() {
        System.out.println("Message: " + message.getMessage());
    }
}

This is the main Application class. The @ComponentScan annotation searches for components. The @Autowired annotation injects the bean into the message variable. The AnnotationConfigApplicationContext is used to create the Spring application context.

My Standalone Spring tutorial shows how to create a standalone Spring application with both XML and annotations.

Configuring Spring in Stand-Alone Apps, It can strongly benefit applications as a whole. Sometimes, you need to create your own highly customized stand-alone application instead using  I'm trying to create an executable-jar standalone application with annotation-based autowiring, but I can't get the runnable jar file (exported from Eclipse as runnable JAR file) to do it's job. It does run as Java application from Eclipse directly, just not as standalone app via console > java -jar test.jar .

For Spring 4, using Spring Boot we can have the following example without using the anti-pattern of getting the Bean from the ApplicationContext directly:

package com.yourproject;

@SpringBootApplication
public class TestBed implements CommandLineRunner {

    private MyService myService;

    @Autowired
    public TestBed(MyService myService){
        this.myService = myService;
    }

    public static void main(String... args) {
        SpringApplication.run(TestBed.class, args);
    }

    @Override
    public void run(String... strings) throws Exception {
        System.out.println("myService: " + MyService );
    }

}

@Service 
public class MyService{
    public String getSomething() {
        return "something";
    }
}

Make sure that all your injected services are under com.yourproject or its subpackages.

Autowiring in Spring, In this post, I'll explain how to work with autowiring in Spring. 3. Autowiring '​byType': This option enables the autowire based on bean type. Now, our Spring application is ready with all types of Spring autowiring. So, let's  i am looking for samples or tutorials of using Spring in a standalone (desktop/swing) application, i searched a lot but couldn't get to something useful, all the examples and tutorials are for web applications, please advise.

A nice solution would be to do following,

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContext implements ApplicationContextAware {

private static ApplicationContext context;

/**
 * Returns the Spring managed bean instance of the given class type if it exists.
 * Returns null otherwise.
 * @param beanClass
 * @return
 */
public static <T extends Object> T getBean(Class<T> beanClass) {
    return context.getBean(beanClass);
}

@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {

    // store ApplicationContext reference to access required beans later on
    SpringContext.context = context;
}
}

Then you can use it like:

YourClass yourClass = SpringContext.getBean(YourClass.class);

I found this very nice solution in the following website: https://confluence.jaytaala.com/pages/viewpage.action?pageId=18579463

Standalone Spring applications - XML and annotations, applications. One application will use an XML file, the other one annotations. Spring is a popular Java application framework. With the @Autowired annotation, the Message bean is injected into the message variable. Spring Boot provides various starters for building standalone or more traditional war deployments. We will create Spring Boot standalone application by im plementing CommnadLineRunner interface. 1. Project Creation There are multiple ways to create a Spring Boot application. Using Maven Using Your IDE (Eclipse, IntelliJ) Spring initializr; We

I case you are running SpringBoot:

I just had the same problem, that I could not Autowire one of my services from the static main method.

See below an approach in case you are relying on SpringApplication.run:

@SpringBootApplication
public class PricingOnlineApplication {

    @Autowired
    OrchestratorService orchestratorService;

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(PricingOnlineApplication.class, args);
        PricingOnlineApplication application = context.getBean(PricingOnlineApplication.class);

        application.start();
    }

    private void start() {
        orchestratorService.performPricingRequest(null);
    }

}

I noticed that SpringApplication.run returns a context which can be used similar to the above described approaches. From there, it is exactly the same as above ;-)

Spring Framework Reference Documentation, 7.4.3. Using depends-on; 7.4.4. Lazy-initialized beans; 7.4.5. Autowiring to java​.util.logging , either in a standalone application (with a custom or default JUL  Bean Autowiring Modes. There are five bean autowiring modes which can be used to instruct Spring container to use bean autowiring for dependency injection.In above syntax we have used the autowire attribute of the element to specify autowire mode for a bean definition.

3. The IoC container - Project Metadata API Guide, In standalone applications it is common to create an instance of Thus you can define beans external to your application classes by using Java rather than XML The Spring container can autowire relationships between collaborating beans. Spring is a powerful framework — and not only for dependency injection. It can strongly benefit applications as a whole. Sometimes, you need to create your own highly customized stand-alone

How to autowire interface in spring boot, 5, the @Autowired annotation can be applied to Spring is a popular Java 3. Secondly, in case of spring, you can inject any implementation at runtime. It helps create stand-alone, production-grade Spring based applications with minimal  Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. 3: Create Java classes TextEditor, SpellChecker and MainApp under the com.tutorialspoint package. 4: Create Beans configuration file Beans.xml under the src folder. 5: The final step is to create the content of all the Java files

Spring Autowire Example, In this example we shall show you how to use Spring Autowiring We are also using Spring version 3.2.3 and the JDK 7_u_21. /src/main/java folder, that contains source files for the dynamic content of the application,  @Configuration @ComponentScan("com.baeldung.autowire.sample") public class AppConfig {} As an alternative, in Spring XML, it can be enabled by declaring it in Spring XML files like so: <context:annotation-config/> 3. Using @Autowired

Comments
  • Make some effort to make your question readable. And show us the exception stack trace.
  • I maintain an operational example here: tshikatshikaaa.blogspot.com/2012/08/…
  • Isn't @Autowired an all-in strategy? Either spring manages all the object creation none, but you can't add @Autowired to some fields in your callstack and instantiate them with new ..().
  • @Cojones, you can autowire some beans and create others with new, otherwise how would you ever be able to call new ArrayList(), for example? If you have a class with autowired parameters and you instantiate it with new then the autowiring won't take place.
  • You might need this in your config.xml also:<context:annotation-config /> <context:component-scan base-package="com.yourcompany.mycomponents" />
  • Don't forget the @Component annotation above Main, otherwise you'll get a No qualifying bean of type [..] is defined exception. Took me some time to figure out.
  • @TinusSky even with that I got No qualifying bean of type..error
  • This solution is much much easier than the xml solutions. Worked for me really well.
  • I am curious why it is needed to autowire and then get the bean from the context.. I think my answer resolves this antipattern
  • @MichailMichailidis You have a Spring Boot application. Here we deal with a classic Spring application. We need to bootstrap the application.
  • Thank you @JanBodnar. I thought all apps now by default are SpringBootApplications either extending CommandLineRunner resembling what you are describing or otherwise starting a web server