Autowire byName example!

in XML configuration!

Initial Example

Directory Layout


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/maven-v4_0_0.xsd">
 
     <modelVersion>4.0.0</modelVersion>
 
     <groupId>biz.tugay</groupId>
     <artifactId>begsprch01</artifactId>
     <packaging>jar</packaging>
 
     <version>1.0-SNAPSHOT</version>
 
     <name>begsprch01</name>
     <url>http://www.tugay.biz</url>
 
     <dependencies>
        <dependency> 
            <groupId>org.springframework</groupId> 
            <artifactId>spring-context</artifactId> 
            <version>4.0.5.RELEASE</version>
        </dependency>
    </dependencies>
 
     <build>
        <finalName>begsprch01</finalName>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>biz.tugay.begsprch01.App</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

Foo.java
package biz.tugay.begsprch01.service;
 
public interface Foo {
    void foo();
    int getCounter();
}

FooImpl.java
package biz.tugay.begsprch01.service;
 
public class FooImpl implements Foo {
 
    private static int counter = 0;
 
    public FooImpl() {
        counter++;
    }
 
    public void foo() {
        System.out.println("FooImpl#foo()");
    }
 
    public int getCounter() {
        return counter;
    }
}

Bar.java
package biz.tugay.begsprch01.service.bar;
 
public interface Bar {
    void bar();
}

BarImpl.java
package biz.tugay.begsprch01.service.bar;
 
import biz.tugay.begsprch01.service.Foo;
 
public class BarImpl implements Bar {
 
    private Foo fooDependency;
 
    public void bar() {
        fooDependency.foo();
    }
 
    public void setFooDependency(final Foo fooDependency) {
        this.fooDependency = fooDependency;
    }
}

beans-service.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" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
                            http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <bean id="foo" class="biz.tugay.begsprch01.service.FooImpl" />
    <bean id="bar" class="biz.tugay.begsprch01.service.bar.BarImpl" autowire="byType" />
 
</beans>

App.java
package biz.tugay.begsprch01;
 
import biz.tugay.begsprch01.service.Foo;
import biz.tugay.begsprch01.service.bar.Bar;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class App {
    public static void main(String[] args) {
        final ApplicationContext appContx = new ClassPathXmlApplicationContext("beans-service.xml");
        final Foo foo = (Foo) appContx.getBean("foo");
        foo.foo();
 
        final Bar bar = appContx.getBean("bar", Bar.class);
        bar.bar();
    }
}

Build & Execute
MacBook-Pro:begsprch01 koraytugay$ mvn -q clean install
MacBook-Pro:begsprch01 koraytugay$ mvn -q exec:java
Sep 11, 2017 8:54:53 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@69a79533: startup date [Mon Sep 11 20:54:53 CEST 2017]; root of context hierarchy
Sep 11, 2017 8:54:53 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans-service.xml]
FooImpl#foo()
FooImpl#foo()

What happens when we add the following class?

FooDummyImpl.java
package biz.tugay.begsprch01.service;
 
public class FooDummyImpl implements Foo {
 
    public void foo() {
        System.out.println("Foo Dummy, hello!");
    }
 
    public int getCounter() {
        return -1;
    }
}

and of course the following bean definition..
<bean id="fooDummy" class="biz.tugay.begsprch01.service.FooDummyImpl" />

Build & Execute
MacBook-Pro:begsprch01 koraytugay$ mvn -q clean install
MacBook-Pro:begsprch01 koraytugay$ mvn -q exec:java
Sep 11, 2017 8:58:24 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@46d961db: startup date [Mon Sep 11 20:58:24 CEST 2017]; root of context hierarchy
Sep 11, 2017 8:58:24 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans-service.xml]
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:java (default-cli) on project begsprch01: An exception occured while executing the Java class. null: InvocationTargetException: Error creating bean with name 'bar' defined in class path resource [beans-service.xml]: Unsatisfied dependency expressed through bean property 'fooDependency': : No qualifying bean of type [biz.tugay.begsprch01.service.Foo] is defined: expected single matching bean but found 2: foo,fooDummy; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [biz.tugay.begsprch01.service.Foo] is defined: expected single matching bean but found 2: foo,fooDummy -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Lets try byName instead of byType
<bean id="bar" class="biz.tugay.begsprch01.service.bar.BarImpl" autowire="byName" />

Build & Execute
MacBook-Pro:begsprch01 koraytugay$ mvn -q exec:java
Sep 11, 2017 9:01:34 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@69a79533: startup date [Mon Sep 11 21:01:34 CEST 2017]; root of context hierarchy
Sep 11, 2017 9:01:34 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans-service.xml]
FooImpl#foo()
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:java (default-cli) on project begsprch01: An exception occured while executing the Java class. null: InvocationTargetException: NullPointerException -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Try Fixing by changing the setterMethodName
public void setFooDummy(final Foo fooDependency) {
    this.fooDependency = fooDependency;
}

Build & Execute
MacBook-Pro:begsprch01 koraytugay$ mvn -q clean install
MacBook-Pro:begsprch01 koraytugay$ mvn -q exec:java
Sep 11, 2017 9:04:31 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@17f86d6e: startup date [Mon Sep 11 21:04:31 CEST 2017]; root of context hierarchy
Sep 11, 2017 9:04:31 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans-service.xml]
FooImpl#foo()
Foo Dummy, hello!

What to Remember?

I think the setter method name must match the bean id when using autowiring byName!