ApplicationContextAware multiple inheritance Bean interface assembly

Background problem

  The use of multi-channel users to send text messages, but only one entrance, and may later abandon or extend the channel, so use inheritance to implement.

  First, some of the parent class defines interfaces Sender send text messages and other basic public methods, notably the following:

public interface Sender {

    void send();
}

  Each channel as a subclass inherits Sender interface, basic method, as follows:

 
 
@Service
public class BaseSender1 implements Sender {
@Override
public void send() {
System.out.println("BaseSender1.send()");
}
}
@Service
public class BaseSender2 implements Sender {
@Override
public void send() {
System.out.println("BaseSender2.send()");
}
}
@Service
public class BaseSender3 implements Sender {
@Override
public void send() {
System.out.println("BaseSender3.send()");
}
}

  When sending text messages, you need to get a set of channels from which to choose to send a text message, here it uses ApplicationContextAware, look at the concrete realization:

@Component
@Slf4j
public class SenderUtil implements ApplicationContextAware {

    private Collection<Sender> senders;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("applicationContext:{}", applicationContext);
        senders = applicationContext.getBeansOfType(Sender.class).values();
        senders.forEach(Sender::send);
    }

    public Collection<Sender> getSenders(){
        return senders;
    }
}

  SenderUtil inheritance ApplicationContextAware interface, setApplicationContext method, setApplicationContext method, we get applicationContext context where access to the Sender Type Bean, and instantiated into the map, the map value obtained last traversal Sender subclasses set.

Implementation process

  Classes interface implemented ApplicationContextAware Spring container, automatically call setApplicationContext method at startup, the applicationContext injection. ApplicationContextAware class implements the interface needs to be registered within the container, may be used @Component annotation in the profile or configuration. When using ApplicationContextAware get the context, must ensure that the code and the code currently running Spring is in the same context, the applicationContext get is empty.

  PS : Why not use ClassPathXmlApplicationContext loading a configuration file to get the context of it, this is possible, but at this time to get the Spring container applicationContext not generate that one, will have redundancy, so do not use this approach.

  

 

Guess you like

Origin www.cnblogs.com/youtang/p/11520882.html