Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 299
Buddhi Avatar asked May 14 '09 19:05

Buddhi


People also ask

How does Spring use dependency injection?

Dependency Injection is a fundamental aspect of the Spring framework, through which the Spring container “injects” objects into other objects or “dependencies”. Simply put, this allows for loose coupling of components and moves the responsibility of managing components onto the container.

Which is used to load a standalone application in Spring?

Spring Boot makes it easy to create stand-alone, production-grade Spring-based applications. Spring Boot provides various starters for building standalone or more traditional war deployments.

Which API is used by Spring framework for dependency injection?

Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods.

Which dependency injection type is not supported by Java Spring directly?

There are three types of injection: Constructor, Setter and Interface. Spring doesn't support the latest directly(as I have observed people saying).


1 Answers

suppose you have:

class Bean1 {
  Bean2 bean2;
}

class Bean2 {
  String data;
}

the context.xml file

<bean id="bean1" class="Bean1">
  <property name="bean2" ref="bean2" />
</bean>

<bean id="bean2" class="Bean2" />

then this should be true

ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"context.xml"});
Bean1 bean1 = (Bean1) context.getBean("bean1");

// bean1.bean2 should not be null here.
like image 132
Mihai Toader Avatar answered Oct 13 '22 01:10

Mihai Toader