B.java
This class contains a constructor and method only.
[java]package splesson;
public class B {
B(){System.out.println("b is created");}
void print(){System.out.println("hello b");}
} [/java]
A.java
This class contains reference of B class and constructor and method.
[java]package splesson;
public class A {
B b;
A(){System.out.println("a is created");}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
void print(){System.out.println("hello a");}
void display(){
print();
b.print();
}
} [/java]
Test.java
This class gets the bean from the applicationContext.xml file and calls the display method.
[java]package splesson;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
A a=context.getBean("a",A.class);
a.display();
}
} [/java]
The
Application Context is spring's more best in class holder. Like
BeanFactory it can stack bean definitions, wire beans together and administer beans upon solicitation. Also it includes more enterprise-specific usefulness, for example, the capacity to determine literary messages from a properties document and the capacity to distribute application events to interested event listeners. This container is characterized by the
org.springframework.context.ApplicationContext interface.
applicationContext.xml
[xml]<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="b" class="splesson.B"></bean>
<bean id="a" class="splesson.A" autowire="byName"></bean>
</beans> [/xml]
Output
When compile the code following is the output will be generated.
[java]b is created
a is created
hello a
hello b[/java]
In case of byName autowiring mode, bean id and reference name must be same.It internally uses setter injection.
[java]<bean id="b" class="splesson.B"></bean>
<bean id="a" class="splesson.A" autowire="byName"></bean> [/java]
But, if you change the name of bean, it will not inject the dependency as follows.
[java]<bean id="b1" class="splesson.B"></bean>
<bean id="a" class="splesson.A" autowire="byName"></bean> [/java]