通过自定义注解发布Hessian服务

找到新工作了,跳槽成功...然后还没去,但是通过面试知道了他们rpc框架用到了hessian,于是进行恶补..就看到了关于注解方式发布,之前如果springmvc集成发布写xml或写方法很累..

1.编写自定义注解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Service
public @interface HessianX {
    String url();
}

2.编写测试接口和实现类,并加上注解:

@HessianX(url = "hessianX")
public class IndexServiceImpl3 implements IndexService3 {
    @Override
    public String index(String str) {
        return str;
    }
}

3.编写配置类,启动时扫描自定义注解类,进行注入:

@Component
public class WebConfig implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        String[] beanNames = beanFactory.getBeanNamesForAnnotation(HessianX.class);
        if (beanNames == null || beanNames.length < 1) {
            return;
        }
        for (String beanName : beanNames) {
            String beanClassName = beanFactory.getBeanDefinition(beanName).getBeanClassName();
            Class<?> aClass = null;
            try {
                aClass = Class.forName(beanClassName);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            HessianX annotation = aClass.getAnnotation(HessianX.class);
            String url = annotation.url();
            if (!url.startsWith("/")) {
                url = "/" + url;
            }
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(HessianServiceExporter.class);
            builder.addPropertyReference("service", beanName);
            builder.addPropertyValue("serviceInterface", aClass.getInterfaces()[0].getName());
            ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(url, builder.getBeanDefinition());
        }
    }
}

4.然后最后测试:

 @Test
    public void test3() throws MalformedURLException {
        String url = "http://localhost:8080/hessianX";
        HessianProxyFactory factory = new HessianProxyFactory();
        IndexService3 userService3 = (IndexService3) factory.create(IndexService3.class, url);
        System.out.println(userService3.index("测试"));
    }

 

注意了:

发布的服务,其所谓beanName一定要带"/";其次如果集成了springmvc,那么发布时候如果通过xml或者注解@Bean发布,那么确保要写入springmvc分发器配置文件中或者要扫描到注解位置;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值