myfunnyfella
myfunnyfella

Reputation: 1467

Stuck converting Spring xml config to java config

I stuck converting my current test app in Spring from using XML configuration to using Java configuration...

I have the following files

App.java

package com.spring.ioc.DependencyInjection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

 public class App {
    public static void main(String[] args) {
     ApplicationContext ctx = new ClassPathXmlApplicationContext("app-config.xml");
        Phone p = ctx.getBean("phone", Phone.class);
     p.calling();
     p.data();

    }
}

Galaxy.java

package com.spring.ioc.DependencyInjection;

public class Galaxy implements Phone {
    public void calling() {
        System.out.println("Calling using Galaxy");
    }
    public void data() {
        System.out.println("Browsing internet using Galaxy");
    }
}

IPhone.java

package com.spring.ioc.DependencyInjection;

public class IPhone implements Phone {
    public void calling() {
        System.out.println("Calling using iPhone");
    }
    public void data() {
        System.out.println("Browsing internet using iPhone");
    }
}

Phone.java

package com.spring.ioc.DependencyInjection;

public interface Phone {
    void calling();

    void data();
}

app-config.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
        
      <bean id="phone" class="com.spring.ioc.DependencyInjection.IPhone"></bean>  
        
 </beans>

The code above allows me to demo how you can use XML & edit the text between 'IPhone' or 'Galaxy' by changing the bean name at the end of the fully qualified name

<bean id="phone" class="com.spring.ioc.DependencyInjection.IPhone"></bean> or <bean id="phone" class="com.spring.ioc.DependencyInjection.Galaxy"></bean>

How can do the same in using JavaConfig instead of XML config?

I know how to use Java configuration to just pull one bean but am lost how to set it up to alternate between two objects.

Can you please show me by modifying the code I provided or adding any other code needed?

Upvotes: 0

Views: 57

Answers (1)

dharam
dharam

Reputation: 8106

I believe you can use

@Component("iphone")
public class IPhone {}

@Component("galaxy ")
public class Galaxy {}

and where you inject it,

@Autowired
@Qualifier(value = "iphone")
private Phone iPhone;

@Autowired
@Qualifier(value = "galaxy")
private Phone galaxy;

Upvotes: 1

Related Questions