A very beginner approach to get new objects in Spring framework is to either use BeanFactory or ApplicationContext. Since books on Spring describe ApplicationContext as having extra features over BeanFactory, many developers end up writing code which involved getting a bean instance by using code which looks like:

ApplicationContext empContext = new ClassPathXmlApplicationContext(
	"somebean-module.xml");
Bean bean = (EmployeeList) empContext.getBean("bean");

In this way the use of new operator is avoided and you get a bean instances depending upon the configuration of that bean (singleton, prototype, setter injection or constructor injection).

Issues with ApplicationContext.getBean

But the problem with using this approach is that:

  • It can result in issues in multi-threaded applications.
  • Everywhere in your code, such repetitive code shall be present where you are getting a bean instance from ApplicationContext. Such code doesn’t make your application maintainable.
  • There is nothing automatic in explicitly using getBean method of ApplicationContext.

How to avoid ApplicationContext.getBean

There are a number of approaches by which the use of such repetitive code can be avoided as listed here:

1) Spring MVC application :

A Spring web MVC application has the bean instances automatically injected into it. Check out Spring REST Webservice tutorial and see for yourself how the bean instances are getting injected to the controller methods. Here is a reproduction of one method from this controller:

    @RequestMapping(value = "/addEmp", 
			method = RequestMethod.POST)
	public @ResponseBody String addEmployee(@RequestBody Employee emp) {
		for (Iterator<Employee> iterator = list.iterator(); iterator.hasNext();) {
			Employee tempEmp = (Employee) iterator.next();
			if(tempEmp.getEmpId()==emp.getEmpId()) {
				return "Employee already present. No need to add again";
			}
		}
				list.add(emp);
				return "Employee Successfully Added";
	}

In the above code, an instance of Employee class is getting injected into addEmployee method automatically.

2) Autowired annotation :

Use @Autowired annotation to automatically inject and create instances which are dependent on each other. This means that if Class A is dependent on Class B for initialization then Spring will automatically create an instance of class B first and then inject this instance to constructor of Class A. Thus we have got instances of both class A and class B. One can autowire by name, type and constructor.

You may use the @Autowired annotation with any method, constructor or field for dependency injection to happen. Lately JDK has also introduced @Inject annotation which has exactly the same purpose as @Autowired.

3) Reference Bean Injection :

By using the Spring bean configuration file, you can inject an instance of one bean into another. A sample code which you must have seen in many Spring based applications looks like:

<bean id="foo" class="com.example.Foo">...</bean>

<bean id="bar" class="com.example.Bar">
   <property name="foo" ref="foo"/>
</bean>

In the above code, one can easily replace setter injection with constructor injection and still use bean reference for Inversion of Control (IoC).

Conclusion

There are multiple solutions to avoid the use of ApplicationContext.getBean(String …) method. Unless you want a quick hack to demonstrate Spring capabilities or learning Spring IoC, you should avoid using this approach. For Spring MVC applications, there is automatic injection done at many places but for standalone applications, you have auto-wiring and bean reference injection at your disposal.

Related Posts

Alternatives to ApplicationContext.getBean admin Spring
A very beginner approach to get new objects in Spring framework is to either use BeanFactory or ApplicationContext. Since books on Spring describe ApplicationContext as having extra features over BeanFactory, many developers end up writing code which involved getting a bean instance by using code which looks like: ApplicationContext empContext...
A very beginner approach to get new objects in Spring framework is to either use BeanFactory or ApplicationContext. Since books on Spring describe ApplicationContext as having extra features over BeanFactory, many developers end up writing code which involved getting a bean instance by using code which looks like: 1 In this way the use of new operator is avoided and you get a bean instances depending upon the configuration of that bean (<a href="http://www.javaexperience.com/bean-scopes-in-spring/">singleton, prototype</a>, <a href="http://www.javaexperience.com/dependency-injection-types-in-spring-framework/">setter injection or constructor injection</a>). <h2>Issues with ApplicationContext.getBean</h2> But the problem with using this approach is that: <ul> <li> It can result in issues in multi-threaded applications.</li> <li> Everywhere in your code, such repetitive code shall be present where you are getting a bean instance from ApplicationContext. Such code doesn't make your application maintainable.</li> <li> There is nothing automatic in explicitly using getBean method of ApplicationContext.</li> </ul> <h2>How to avoid ApplicationContext.getBean</h2> There are a number of approaches by which the use of such repetitive code can be avoided as listed here: <h3>1) Spring MVC application :</h3> A Spring web MVC application has the bean instances automatically injected into it. Check out <a href="http://www.javaexperience.com/spring-restful-web-service-tutorial/">Spring REST Webservice tutorial</a> and see for yourself how the bean instances are getting injected to the controller methods. Here is a reproduction of one method from this controller: 1 In the above code, an instance of Employee class is getting injected into addEmployee method automatically. <h3>2) Autowired annotation :</h3> Use @Autowired annotation to automatically inject and create instances which are dependent on each other. This means that if Class A is dependent on Class B for initialization then Spring will automatically create an instance of class B first and then inject this instance to constructor of Class A. Thus we have got instances of both class A and class B. One can autowire by name, type and constructor. You may use the @Autowired annotation with any method, constructor or field for dependency injection to happen. Lately JDK has also introduced @Inject annotation which has exactly the same purpose as @Autowired. <h3>3) Reference Bean Injection :</h3> By using the Spring bean configuration file, you can inject an instance of one bean into another. A sample code which you must have seen in many Spring based applications looks like: 1 In the above code, one can easily replace setter injection with constructor injection and still use bean reference for Inversion of Control (IoC). <h2>Conclusion</h2> There are multiple solutions to avoid the use of ApplicationContext.getBean(String ...) method. Unless you want a quick hack to demonstrate Spring capabilities or learning Spring IoC, you should avoid using this approach. For Spring MVC applications, there is automatic injection done at many places but for standalone applications, you have auto-wiring and bean reference injection at your disposal.
HTTP Basic authentication in Spring REST web services
Spring RESTful Web Service Tutorial
The following two tabs change content below.
I run this blog with lots of passion. In this website, you will find tutorials on Core Java, Spring, Struts, Web Applications, Portals and Database. Please support me and the website by sharing the posts on your facebook / twitter. You can tap the share button at the top of each post. Thanks for the support.

Comments

comments