java—提供静态接口以使用spring访问bean

ivqmmu1c  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(348)

我创造了很多 MessageChannel s、 每个包裹在单独的物体中 Sender .

@Configuration
public class WebSocketSendersConfig {

    @Bean
    public Sender heartBeatSender(
            HeartBeatWebSocketChannel channel,
            @Qualifier("mappingJackson2MessageConverter") MessageConverter converter
    ) {
        return createSender(channel, converter);
    }

    @Bean
    public Sender upperCaseSender(
           UpperCaseWebSocketChannel channel, 
           @Qualifier("mappingJackson2MessageConverter") MessageConverter converter  
    ) {
        return createSender(channel, converter);
    }

    @Bean
    public Sender ...

    ...

现在如果我想通过sender(messagechannel)发送消息 heartBeat 我可以做到:

@Autowired
@Qualifier("heartBeat") heartBeatSender;

sendToHeartBeat(Message<?> msg) {
    heartBeatSender.send(msg);
}

我想摆脱自动连线,通过静态方法访问选定的发送方(messagechannel):

@Service
public class WebSocketSenders {

    private static Sender heartBeatSender;
    private static Sender upperCaseSender;
    private static Sender lowerCaseSender;

    @Autowired
    public WebSocketSendersAccessor(
            @Qualifier("heartBeatSender") Sender heartBeatSender,
            @Qualifier("upperCaseSender") Sender upperCaseSender,
            @Qualifier("lowerCaseSender") Sender lowerCaseSender
    ) {
        this.heartBeatSender = heartBeatSender;
        this.upperCaseSender = upperCaseSender;
        this.lowerCaseSender = lowerCaseSender;
    }

    public static Sender HEART_BEAT() {
        return heartBeatSender;
    }

    public static Sender UPPER_CASE() {
        return upperCaseSender;
    }

    public static Sender LOWER_CASE() {
        return lowerCaseSender;
    }
}

现在我可以通过静态方法访问它:

@Autowired
WebSocketSendersAccessor accessor;

sendToHeartBeat(Message<?> msg) {
    accessor.HEART_BEAT().send(msg);
}

现在我必须自动连接访问器类。
如何通过去掉autowiring访问器类来改进这一点?

xhv8bpkk

xhv8bpkk1#

你可以用 InitializingBean 接口:

@Service
@AllArgsConstructor
public class WebSocketSenders  implements InitializingBean {

    @Qualifier("heartBeatSender") private final Sender heartBeatSender;
    @Qualifier("upperCaseSender") private final Sender upperCaseSender;
    @Qualifier("lowerCaseSender") private final Sender lowerCaseSender;

    @Override
    public void afterPropertiesSet() throws Exception {
        SomeClass.staticHeartBeatSender = heartBeatSender;
        ...
    }
    ...
}
class SomeClass {
   static Sender staticHeartBeatSender;
   sendToHeartBeat(Message<?> msg) {
      staticHeartBeatSender.send(msg);
   }
}

相关问题