spring注解的一些使用

1 条件注入
一个接口有多种实现,但有的时候只需要使用其中一个实现,这种方式就用到了@ConditionalOnProperty,例如下面的例子,就通过了ws.tio.config.mqType这个注解值来生成,注释使用的时候使用@Resource

public interface MqMsgService {
    /**
     * 生产消息
     * @param topic 主题
     * @param msg 消息
     * @return
     */
    boolean produce(String topic, String msg);
}

这是一个rabbitmq的生产者实现

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@ConditionalOnProperty(name = "ws.tio.config.mqType", havingValue = "rabbitmq")
public class RabbitMqMsgService implements MqMsgService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public boolean produce(String topic, String msg) {
        try{
            rabbitTemplate.convertAndSend(topic, msg);
        } catch(Exception e){
            log.error(e.getMessage(),e, msg);
            throw new RuntimeException("发行消息失败",e);
        }
        return true;
    }
}

这是redis的生产者实现

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@ConditionalOnProperty(name = "ws.tio.config.mqType", havingValue = "redis")
public class RedisMqMsgService implements MqMsgService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean produce(String topic, String msg) {
        try{
            stringRedisTemplate.convertAndSend(topic, msg);
        } catch(Exception e){
            log.error(e.getMessage(),e, msg);
            throw new RuntimeException("发行消息失败",e);
        }
        return true;
    }
}

2 策略工厂
还是一个接口多个实现,使用spring的上下文可以做,还有一种办法就是使用策略工厂,下面的@Autowired会将对象的实现类装载进去

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description
 * @Author dzm
 * @Date 2021-09-10 11:14
 */
@Service
public class MqMsgFactory {

    /**
     * 自动注解
     */
    @Autowired
    Map<String, MqMsgService> mqMap = new ConcurrentHashMap<>(2);

    /**
     * 获取消息处理的生产者
     * @param componet
     * @return
     */
    public MqMsgService getMqMsgService(String componet){
        MqMsgService mqMsgService = mqMap.get(componet);
        if (mqMsgService == null){
            throw new RuntimeException("策略没有定义");
        }
        return mqMsgService;
    }
}

3 多对象
websocket是多对象的,故而在@ServerEndpoint中是无法直接注入单例的类,
SpringBoot使用@ServerEndpoint无法依赖注入问题解决(WebSocket
websocket注入service对象的方法
上面的链接有不正确的地方,如果是web工程,是可以通过ApplicationContext拿到bean的,但是springboot却不行,这里一种实现方式是,在装在的时候给内部的静态变量赋值。

@Slf4j
@Component
@ServerEndpoint("/websocket/{username}")
public class WebSocketServiceImpl implements WebSocketService {

    private static CopyOnWriteArraySet<WebSocketServiceImpl> webSockets =new CopyOnWriteArraySet<>();

    public static CacheManager cacheManager;
    }

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Autowired
    public void setWebsocketCache(CacheManager cacheManager){
        WebSocketServiceImpl.cacheManager = cacheManager;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

warrah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值