spring常用代码

本文介绍了如何在Spring Boot应用中使用RpcServer实现Bean的自动配置,包括依赖注入、初始化方法调用、BeanNameAware、ApplicationContextAware等机制,以及销毁过程中的@PreDestroy注解和DisposableBean接口的运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


import java.util.Map;

/**
 * RPC Server
 * <p>
 * 1:如果bean实现了 BeanNameAware接口,则调用BeanNameAware.setBeanName()
 * 2:如果bean实现了BeanFactoryAware接口,则调用BeanFactoryAware.setBeanFactory()
 * 3:如果bean实现了ApplicationContextAware接口,则调用ApplicationContextAware.setApplicationContext()
 * 4:@PostConstruct 注解指定的初始化方法
 * 5:如果bean实现了InitializingBean接口,则调用InitializingBean.afterPropertiesSet()
 * 6:调用<bean>的init-method属性指定的初始化方法
 * 7:@PreDestroy注解指定的销毁方法 如果bean实现了DiposibleBean接口,则调用DiposibleBean.destory()
 * 8:调用<bean>的destroy-method属性指定的初始化方法
 */
public class RpcServer extends NettyServer implements ApplicationContextAware, InitializingBean, DisposableBean {

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        Map<String, Object> serviceBeanMap = ctx.getBeansWithAnnotation(NettyRpcService.class);
        if (MapUtils.isNotEmpty(serviceBeanMap)) {
            for (Object serviceBean : serviceBeanMap.values()) {
                NettyRpcService nettyRpcService = serviceBean.getClass().getAnnotation(NettyRpcService.class);
                String interfaceName = nettyRpcService.value().getName();
                String version = nettyRpcService.version();
                super.addService(interfaceName, version, serviceBean);
            }
        }
    }

    @Override
    public void afterPropertiesSet() {

    }

    @Override
    public void destroy() {

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值