1
votes

I am working on Spring auto wiring using spring configuration file(xml configuration). I want to inject beans based on a condition. Let me go into details.

  • There are two classes 'EmailSender' and 'SmsSender' which implement the interface IMessageSender. Beans are configured for both classes in the configurations file.

enter image description here

  • I have another class SenderUser which has a instance variable of type IMessageSender in it.

    package org.pradeep.core;

    public class SenderUser { private String name; private String Type;

    private IMessageSender msg;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getType() {
        return Type;
    }
    
    public void setType(String type) {
        Type = type;
    }
    
    public IMessageSender getMsg() {
        return msg;
    }
    
    public void setMsg(IMessageSender msg) {
        this.msg = msg;
    }
    

    }

    • I want to inject IMessageSender into bean of SenderUser based on the value of SenderUser.getType(). That means first SernderUser.type should be set and then based on it's value (if value is 'email' then bean with the name 'email' should be wired else bean with the name 'sms' should be wired.) msg should be wired.

Please help me resolve the issue.

3

3 Answers

1
votes

I believe the best approach is to implement a BeanFactory for SenderUser. Take a look at this post for an idea.

0
votes

Interfaces can't be injected, they aren't beans/instances.

0
votes

you may use SPEL

<bean id="user" class="SenderUser" autowire="byType">
  <property name="type" value="email"/>
  <property name="msg" value="#{type != null && type == 'email' ? email : sms}"/>
</bean>

<bean id="email" class="EmailSender"/>
<bean id="sms" class="SmsSender"/>