JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Spring auto-wiring using @Autowired annotation example


You have seen multiple ways of injecting beans using different auto-wiring modes on xml based configuration file. Spring also provides annotation based auto-wiring by providing @Autowired annotation. you can use @Autowired annotation to auto wire spring bean on setter method, instance variable, and constructor. If you use @Autowired annotation, spring container auto-wires the bean by matching data type.

This page shows an example for how to use @Autowired annotation on setter method, instance variable and constructor. Here is the simple spring bean:

package com.java2novice.beans;

public class Order {

	private String item;
	
	private String price;
	
	public String getItem() {
		return item;
	}
	public void setItem(String item) {
		this.item = item;
	}
	public String getPrice() {
		return price;
	}
	public void setPrice(String price) {
		this.price = price;
	}
}

To use auto-wire feature through annotations, you must include annotation-config tag with in your xml based configuration file:

<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 />
    
    <bean id="paymentGateway" class="com.java2novice.beans.PaymentGateway"/>
    
    <bean id="orderBean" class="com.java2novice.beans.Order" >
		<property name="item" value="Java Book" />
		<property name="price" value="RS 225" />
	</bean>
</beans>

@Autowired annotation on instance variable:

package com.java2novice.beans;

import org.springframework.beans.factory.annotation.Autowired;

public class PaymentGateway {

	@Autowired
	private Order order;
	
	@Override
	public String toString(){
		return "ordering "+this.order.getItem()+" | price: "+this.order.getPrice();
	}
}

@Autowired annotation on setter method:

package com.java2novice.beans;

import org.springframework.beans.factory.annotation.Autowired;

public class PaymentGateway {

	private Order order;
	
	public Order getOrder() {
		return order;
	}

	@Autowired
	public void setOrder(Order order) {
		this.order = order;
	}

	@Override
	public String toString(){
		return "ordering "+this.order.getItem()+" | price: "+this.order.getPrice();
	}
}

@Autowired annotation on constructor:

package com.java2novice.beans;

import org.springframework.beans.factory.annotation.Autowired;

public class PaymentGateway {

	private Order order;
	
	@Autowired
	public PaymentGateway(Order ord){
		this.order = ord;
	}

	@Override
	public String toString(){
		return "ordering "+this.order.getItem()+" | price: "+this.order.getPrice();
	}
}

Spring bean demo class:

package com.java2novice.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.java2novice.beans.PaymentGateway;

public class SpringDemo {

	public static void main(String a[]){
		String confFile = "applicationContext.xml";
		ConfigurableApplicationContext context 
						= new ClassPathXmlApplicationContext(confFile);
		PaymentGateway paymentGateway = (PaymentGateway) context.getBean("paymentGateway");
		System.out.println(paymentGateway.toString());
	}
}

Dependency Check: When you use @Autowired, it will make dependency check to make sure proper auto-wiring on property. If spring fails to find matching bean for auto-wiring, it throws an exception. If you don't dependency check, then use "required" attribute of @Autowired annotation, and set it false. Here is an example:

package com.java2novice.beans;

import org.springframework.beans.factory.annotation.Autowired;

public class PaymentGateway {

	private Order order;
	
	@Autowired(required=false)
	public PaymentGateway(Order ord){
		this.order = ord;
	}

	@Override
	public String toString(){
		return "ordering "+this.order.getItem()+" | price: "+this.order.getPrice();
	}
}

Output:
ordering Java Book | price: RS 225
<< Previous Program | Next Program >>
blog comments powered by Disqus

Spring framework examples

  1. Spring 3 hello world example
  2. Spring bean java based configuration using @Configuration and @Bean
  3. How to get spring application context object reference?
  4. How to load multiple spring bean configuration files?
  5. Spring java based configuration @Import example
  6. Spring Dependency Injection and Types
  7. Spring Dependency Injection via setter method
  8. Spring Dependency Injection via Constructor
  9. Constructor overloading issue with spring constructor injection
  10. Constructor vs Setter dependency Injection in Spring
  11. How to inject value into spring bean instance variables?
  12. Spring bean tag properties
  13. Differen types of spring bean scopes
  14. How to inject inner bean in spring?
  15. Set spring bean scope using annotation
  16. How to invoke spring bean init and destroy methods?
  17. Spring bean initialization callback
  18. Spring bean destruction callback
  19. Configure default initialization and destroy method in all spring beans
  20. Spring bean init and destroy methods using annotations
  21. Spring Bean Post Processors
  22. How to read property file in spring using xml based configuration file?
  23. How to read property file in spring 3.0 using java based configuration?
  24. How to inject date into spring bean property?
  25. How to inject date into spring bean with CustomDateEditor?
  26. Spring bean inheritance configuration
  27. Spring dependency checking with @Required annotation
  28. How to define a custom Required-style annotation for dependency checking?
  29. How to inject List into spring bean?
  30. How to inject Set into spring bean?
  31. How to inject Map into spring bean?
  32. How to enable auto component scanning in spring?
  33. Difference between @Component, @Service, @Repository and @Controller
  34. How to filter components in auto scanning?
  35. Spring expression language basic example using xml based configuration.
  36. Spring expression language basic example using annotations.
  37. Bean reference example using spring expression language
  38. Spring expression language operators example
  39. Spring expression language ternary operator example
  40. How to use regular expressions with spring expression language?
  41. How to use collections with spring expression language?
  42. Spring bean auto-wiring modes
  43. Spring auto-wiring mode byName
  44. Spring auto-wiring mode byType
  45. Spring auto-wiring mode constructor
  46. Spring auto-wiring using @Autowired annotation example
  47. Spring auto-wiring using @Qualifier annotation example
  48. Spring log4j configuration
  49. How to schedule jobs using @Scheduled annotation in spring?
  50. Send E-mail using spring 3
  51. Send E-mail with attachment using spring 3
  52. Simple spring JDBC example
  53. Spring JDBC example with JdbcTemplate
  54. Spring JDBC example with JdbcDaoSupport
  55. Spring JDBC query example using JdbcDaoSupport
  56. How to query single column using spring JdbcTemplate?
  57. Spring JDBC batch updates using JdbcTemplate?
  58. Spring AOP Advices - Before advice example - xml based configuration
  59. Spring AOP Advices - After returning advice example - xml based configuration
  60. Spring AOP Advices - After throwing advice example - xml based configuration
  61. Spring AOP Advices - Around advice example - xml based configuration
  62. Spring AOP Advice - Pointcuts – Name match example
  63. Spring AOP Advice - Pointcuts – Regular expression example
  64. Spring AOP - AspectJ - @Before example
  65. Spring AOP - AspectJ - @After example
  66. Spring AOP - AspectJ - @AfterReturning example
  67. Spring AOP - AspectJ - @AfterThrowing example
  68. Spring AOP - AspectJ - @Around example
Knowledge Centre
Different types of Access Modifiers
public: Any thing declared as public can be accessed from anywhere.

private: Any thing declared as private can't be seen outside of its class.

protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages.

default modifier: Can be accessed only to classes in the same package.
Famous Quotations
The greatest obstacle to discovery is not ignorance; it is the illusion of knowledge.
-- Daniel J. Boorstin

About Author

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2017 by Nataraja Gootooru. All Rights Reserved.