Alex Rivera | Logout

Spring- How to use Spring Dependency Injection to write a Standalone Java Application

Asked 2009-05-14T19:11:12.173
11

I want to write a standalone application with IOC, how do I use springs dependency injection in there? I'm using JIdea. There is spring 2.5 support but I want to use spring 3.0 here is the way I tried!

I experience in using Spring MVC we can inject dependencies there in a WebApplicationContext but how do I inject dependencies in a standalone application

I tried this

ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"com\\ttg\\xmlfile.xml"});

but I cannot see that the dependencies are injected by the beans defined there (in the XML file) I put the above code in the main method and two bean definitions for two Objects,in one Java class's constructor I used the other class's object - which was injected to this object - and called a method on that which will print some thing but it didn't worked I thought that the above code creates all the dependencies and injects them but it doesn't seem like that

How do I properly use Springs IOC, dependency injection in my stand alone app which does not contain a WebApplicationContext?

Please mention steps.

Edit
Report

1 Answer

2

If you prefer (mostly) pure java, you can use java config:

@Configuration
pubic class MyConfig {

   @Bean
   public Bean1 bean1() { return new Bean1(); }

   @Bean
   public Bean2 bean2() { return new Bean2(bean1()); }
}

And then to instantiate:

ApplicationContext ctx = 
    new AnnotationConfigApplicationContext(MyConfig.class);

Keep in mind there's some things that pure annotation driven configuration doesn't yet support (such as things like tx:annotation-driven), which you might need some xml glue code for.

<beans>
  <tx:annotation-driven />
  <context:annotation-config/>
  <bean class="MyConfig"/>
</beans>

And then use a standard xml based way of creating the ApplicationContext (like ClasspathXmlApplicationContext, or the spring web context loader, etc...).

answered 2012-07-13T18:40:28.970

Your Answer