找到新工作了,跳槽成功...然后还没去,但是通过面试知道了他们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分发器配置文件中或者要扫描到注解位置;