Search in sources :

Example 6 with SofaService

use of com.alipay.sofa.runtime.api.annotation.SofaService in project sofa-boot by alipay.

the class ServiceBeanFactoryPostProcessor method generateSofaServiceDefinition.

@SuppressWarnings("unchecked")
private void generateSofaServiceDefinition(String beanId, SofaService sofaServiceAnnotation, Class<?> beanClass, BeanDefinition beanDefinition, ConfigurableListableBeanFactory beanFactory) {
    if (sofaServiceAnnotation == null) {
        return;
    }
    AnnotationWrapperBuilder<SofaService> wrapperBuilder = AnnotationWrapperBuilder.wrap(sofaServiceAnnotation).withBinder(binder);
    sofaServiceAnnotation = wrapperBuilder.build();
    Class<?> interfaceType = sofaServiceAnnotation.interfaceType();
    if (interfaceType.equals(void.class)) {
        Class<?>[] interfaces = beanClass.getInterfaces();
        if (beanClass.isInterface() || interfaces == null || interfaces.length == 0) {
            interfaceType = beanClass;
        } else if (interfaces.length == 1) {
            interfaceType = interfaces[0];
        } else {
            throw new FatalBeanException(ErrorCode.convert("01-02004", beanId));
        }
    }
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
    String serviceId = SofaBeanNameGenerator.generateSofaServiceBeanName(interfaceType, sofaServiceAnnotation.uniqueId());
    if (!beanFactory.containsBeanDefinition(serviceId)) {
        builder.getRawBeanDefinition().setScope(beanDefinition.getScope());
        builder.setLazyInit(beanDefinition.isLazyInit());
        builder.getRawBeanDefinition().setBeanClass(ServiceFactoryBean.class);
        builder.addAutowiredProperty(AbstractContractDefinitionParser.SOFA_RUNTIME_CONTEXT);
        builder.addAutowiredProperty(AbstractContractDefinitionParser.BINDING_CONVERTER_FACTORY);
        builder.addAutowiredProperty(AbstractContractDefinitionParser.BINDING_ADAPTER_FACTORY);
        builder.addPropertyValue(AbstractContractDefinitionParser.INTERFACE_CLASS_PROPERTY, interfaceType);
        builder.addPropertyValue(AbstractContractDefinitionParser.UNIQUE_ID_PROPERTY, sofaServiceAnnotation.uniqueId());
        builder.addPropertyValue(AbstractContractDefinitionParser.BINDINGS, getSofaServiceBinding(sofaServiceAnnotation, sofaServiceAnnotation.bindings()));
        builder.addPropertyReference(ServiceDefinitionParser.REF, beanId);
        builder.addPropertyValue(ServiceDefinitionParser.BEAN_ID, beanId);
        builder.addPropertyValue(AbstractContractDefinitionParser.DEFINITION_BUILDING_API_TYPE, true);
        builder.addDependsOn(beanId);
        ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(serviceId, builder.getBeanDefinition());
    } else {
        SofaLogger.warn("SofaService was already registered: {}", serviceId);
    }
}
Also used : BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) FatalBeanException(org.springframework.beans.FatalBeanException) BeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry) SofaService(com.alipay.sofa.runtime.api.annotation.SofaService)

Example 7 with SofaService

use of com.alipay.sofa.runtime.api.annotation.SofaService in project sofa-boot by alipay.

the class ServiceBeanFactoryPostProcessor method generateSofaServiceDefinitionOnMethod.

private void generateSofaServiceDefinitionOnMethod(String beanId, AnnotatedBeanDefinition beanDefinition, BeanDefinitionRegistry registry) {
    Class<?> returnType;
    Class<?> declaringClass;
    List<Method> candidateMethods = new ArrayList<>();
    MethodMetadata methodMetadata = beanDefinition.getFactoryMethodMetadata();
    try {
        returnType = ClassUtils.forName(methodMetadata.getReturnTypeName(), null);
        declaringClass = ClassUtils.forName(methodMetadata.getDeclaringClassName(), null);
    } catch (Throwable throwable) {
        // it's impossible to catch throwable here
        SofaLogger.error(ErrorCode.convert("01-02001", beanId), throwable);
        return;
    }
    if (methodMetadata instanceof StandardMethodMetadata) {
        candidateMethods.add(((StandardMethodMetadata) methodMetadata).getIntrospectedMethod());
    } else {
        for (Method m : declaringClass.getDeclaredMethods()) {
            // check methodName and return type
            if (!m.getName().equals(methodMetadata.getMethodName()) || !m.getReturnType().getTypeName().equals(methodMetadata.getReturnTypeName())) {
                continue;
            }
            // check bean method
            if (!AnnotatedElementUtils.hasAnnotation(m, Bean.class)) {
                continue;
            }
            Bean bean = m.getAnnotation(Bean.class);
            Set<String> beanNames = new HashSet<>();
            beanNames.add(m.getName());
            if (bean != null) {
                beanNames.addAll(Arrays.asList(bean.name()));
                beanNames.addAll(Arrays.asList(bean.value()));
            }
            // check bean name
            if (!beanNames.contains(beanId)) {
                continue;
            }
            candidateMethods.add(m);
        }
    }
    if (candidateMethods.size() == 1) {
        SofaService sofaServiceAnnotation = candidateMethods.get(0).getAnnotation(SofaService.class);
        if (sofaServiceAnnotation == null) {
            sofaServiceAnnotation = returnType.getAnnotation(SofaService.class);
        }
        generateSofaServiceDefinition(beanId, sofaServiceAnnotation, returnType, beanDefinition, registry);
        generateSofaReferenceDefinition(beanId, candidateMethods.get(0), registry);
    } else if (candidateMethods.size() > 1) {
        for (Method m : candidateMethods) {
            if (AnnotatedElementUtils.hasAnnotation(m, SofaService.class) || AnnotatedElementUtils.hasAnnotation(returnType, SofaService.class)) {
                throw new FatalBeanException(ErrorCode.convert("01-02002", declaringClass.getCanonicalName()));
            }
            if (Stream.of(m.getParameterAnnotations()).flatMap(Stream::of).anyMatch(annotation -> annotation instanceof SofaReference)) {
                throw new FatalBeanException(ErrorCode.convert("01-02003", declaringClass.getCanonicalName()));
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) BeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) ServiceFactoryBean(com.alipay.sofa.runtime.spring.factory.ServiceFactoryBean) SofaBeanNameGenerator(com.alipay.sofa.runtime.spring.bean.SofaBeanNameGenerator) SofaServiceBinding(com.alipay.sofa.runtime.api.annotation.SofaServiceBinding) SofaLogger(com.alipay.sofa.runtime.log.SofaLogger) Method(java.lang.reflect.Method) ReferenceFactoryBean(com.alipay.sofa.runtime.spring.factory.ReferenceFactoryBean) ClassUtils(org.springframework.util.ClassUtils) MethodMetadata(org.springframework.core.type.MethodMetadata) AbstractContractDefinitionParser(com.alipay.sofa.runtime.spring.parser.AbstractContractDefinitionParser) AnnotationUtils(org.springframework.core.annotation.AnnotationUtils) Set(java.util.Set) ServiceRuntimeException(com.alipay.sofa.runtime.api.ServiceRuntimeException) BindingConverter(com.alipay.sofa.runtime.spi.service.BindingConverter) Collectors(java.util.stream.Collectors) List(java.util.List) BindingConverterContext(com.alipay.sofa.runtime.spi.service.BindingConverterContext) Stream(java.util.stream.Stream) SofaReference(com.alipay.sofa.runtime.api.annotation.SofaReference) Environment(org.springframework.core.env.Environment) Binding(com.alipay.sofa.runtime.spi.binding.Binding) Annotation(java.lang.annotation.Annotation) BindingConverterFactory(com.alipay.sofa.runtime.spi.service.BindingConverterFactory) ApplicationContextAware(org.springframework.context.ApplicationContextAware) PlaceHolderBinder(com.alipay.sofa.boot.annotation.PlaceHolderBinder) AnnotatedElementUtils(org.springframework.core.annotation.AnnotatedElementUtils) Ordered(org.springframework.core.Ordered) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) BindingType(com.alipay.sofa.runtime.api.binding.BindingType) AnnotatedBeanDefinition(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition) JvmBinding(com.alipay.sofa.runtime.service.binding.JvmBinding) BeanDefinitionUtil(com.alipay.sofa.boot.util.BeanDefinitionUtil) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ServiceDefinitionParser(com.alipay.sofa.runtime.spring.parser.ServiceDefinitionParser) SofaRuntimeContext(com.alipay.sofa.runtime.spi.component.SofaRuntimeContext) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ErrorCode(com.alipay.sofa.boot.error.ErrorCode) SofaService(com.alipay.sofa.runtime.api.annotation.SofaService) AnnotatedGenericBeanDefinition(org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition) Order(org.springframework.core.annotation.Order) ScannedGenericBeanDefinition(org.springframework.context.annotation.ScannedGenericBeanDefinition) FatalBeanException(org.springframework.beans.FatalBeanException) ObjectUtils(org.springframework.util.ObjectUtils) StandardMethodMetadata(org.springframework.core.type.StandardMethodMetadata) BeansException(org.springframework.beans.BeansException) GenericBeanDefinition(org.springframework.beans.factory.support.GenericBeanDefinition) BeanDefinitionRegistryPostProcessor(org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor) ApplicationContext(org.springframework.context.ApplicationContext) EnvironmentAware(org.springframework.context.EnvironmentAware) Bean(org.springframework.context.annotation.Bean) SofaReferenceBinding(com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding) AnnotationWrapperBuilder(com.alipay.sofa.boot.annotation.PlaceHolderAnnotationInvocationHandler.AnnotationWrapperBuilder) Assert(org.springframework.util.Assert) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) StandardMethodMetadata(org.springframework.core.type.StandardMethodMetadata) SofaService(com.alipay.sofa.runtime.api.annotation.SofaService) ServiceFactoryBean(com.alipay.sofa.runtime.spring.factory.ServiceFactoryBean) ReferenceFactoryBean(com.alipay.sofa.runtime.spring.factory.ReferenceFactoryBean) Bean(org.springframework.context.annotation.Bean) SofaReference(com.alipay.sofa.runtime.api.annotation.SofaReference) FatalBeanException(org.springframework.beans.FatalBeanException) MethodMetadata(org.springframework.core.type.MethodMetadata) StandardMethodMetadata(org.springframework.core.type.StandardMethodMetadata) Stream(java.util.stream.Stream) HashSet(java.util.HashSet)

Example 8 with SofaService

use of com.alipay.sofa.runtime.api.annotation.SofaService in project sofa-boot by alipay.

the class ServiceBeanFactoryPostProcessor method generateSofaServiceDefinitionOnClass.

private void generateSofaServiceDefinitionOnClass(String beanId, Class<?> beanClass, BeanDefinition beanDefinition, BeanDefinitionRegistry registry) {
    // See issue: https://github.com/sofastack/sofa-boot/issues/835
    SofaService sofaServiceAnnotation = AnnotationUtils.findAnnotation(beanClass, SofaService.class);
    generateSofaServiceDefinition(beanId, sofaServiceAnnotation, beanClass, beanDefinition, registry);
}
Also used : SofaService(com.alipay.sofa.runtime.api.annotation.SofaService)

Example 9 with SofaService

use of com.alipay.sofa.runtime.api.annotation.SofaService in project sofa-boot by alipay.

the class AnnotationPlaceHolderTest method testServiceAnnotationPlaceHolder.

@Test
@SuppressWarnings("unchecked")
public void testServiceAnnotationPlaceHolder() {
    PlaceHolderBinder binder = new PlaceHolderBinder() {

        @Override
        public String bind(String origin) {
            return environment.resolvePlaceholders(origin);
        }
    };
    SofaService sofaService = AnnotationSampleService.class.getAnnotation(SofaService.class);
    PlaceHolderAnnotationInvocationHandler.AnnotationWrapperBuilder<SofaService> builder = PlaceHolderAnnotationInvocationHandler.AnnotationWrapperBuilder.wrap(sofaService).withBinder(binder);
    SofaService delegate = builder.build();
    Assert.assertEquals(sofaService.hashCode(), delegate.hashCode());
    Assert.assertEquals(sofaService.toString(), delegate.toString());
    Assert.assertEquals(SampleService.class, sofaService.interfaceType());
    Assert.assertEquals(SampleService.class, delegate.interfaceType());
    Assert.assertEquals("${annotation.sample.service.uniqueId}", sofaService.uniqueId());
    Assert.assertEquals("annotation-sample-service-uniqueId", delegate.uniqueId());
    Assert.assertEquals(1, sofaService.bindings().length);
    Assert.assertEquals(1, delegate.bindings().length);
    SofaServiceBinding binding = sofaService.bindings()[0];
    String[] filters = binding.filters();
    SofaServiceBinding delegateBinding = delegate.bindings()[0];
    String[] delegateFilters = delegateBinding.filters();
    Assert.assertEquals("${annotation.sample.service.bindingType}", binding.bindingType());
    Assert.assertEquals("bolt", delegateBinding.bindingType());
    Assert.assertEquals(300, binding.timeout());
    Assert.assertEquals(300, delegateBinding.timeout());
    Assert.assertEquals(2, filters.length);
    Assert.assertEquals(2, delegateFilters.length);
    Assert.assertEquals("${annotation.sample.service.filter-1}", filters[0]);
    Assert.assertEquals("service-filter-1", delegateFilters[0]);
    Assert.assertEquals("filter-2", filters[1]);
    Assert.assertEquals("filter-2", delegateFilters[1]);
    Assert.assertTrue(delegate instanceof WrapperAnnotation);
    Assert.assertTrue(delegateBinding instanceof WrapperAnnotation);
}
Also used : SofaServiceBinding(com.alipay.sofa.runtime.api.annotation.SofaServiceBinding) PlaceHolderAnnotationInvocationHandler(com.alipay.sofa.boot.annotation.PlaceHolderAnnotationInvocationHandler) PlaceHolderBinder(com.alipay.sofa.boot.annotation.PlaceHolderBinder) SofaService(com.alipay.sofa.runtime.api.annotation.SofaService) WrapperAnnotation(com.alipay.sofa.boot.annotation.WrapperAnnotation) Test(org.junit.Test)

Example 10 with SofaService

use of com.alipay.sofa.runtime.api.annotation.SofaService in project sofa-boot by alipay.

the class ServiceAnnotationBeanPostProcessor method processSofaService.

private void processSofaService(Object bean, String beanName) {
    final Class<?> beanClass = AopProxyUtils.ultimateTargetClass(bean);
    SofaService sofaServiceAnnotation = beanClass.getAnnotation(SofaService.class);
    if (sofaServiceAnnotation == null) {
        return;
    }
    Class<?> interfaceType = sofaServiceAnnotation.interfaceType();
    if (interfaceType.equals(void.class)) {
        Class<?>[] interfaces = beanClass.getInterfaces();
        if (interfaces == null || interfaces.length == 0 || interfaces.length > 1) {
            throw new ServiceRuntimeException("Bean " + beanName + " does not has any interface or has more than one interface.");
        }
        interfaceType = interfaces[0];
    }
    Implementation implementation = new SpringImplementationImpl(beanName, applicationContext);
    implementation.setTarget(bean);
    Service service = new ServiceImpl(sofaServiceAnnotation.uniqueId(), interfaceType, InterfaceMode.annotation, bean);
    service.addBinding(new JvmBinding());
    ComponentInfo componentInfo = new ServiceComponent(implementation, service, sofaRuntimeContext);
    sofaRuntimeContext.getComponentManager().register(componentInfo);
}
Also used : ServiceComponent(com.alipay.sofa.runtime.service.component.ServiceComponent) ServiceImpl(com.alipay.sofa.runtime.service.component.impl.ServiceImpl) Service(com.alipay.sofa.runtime.service.component.Service) SofaService(com.alipay.sofa.runtime.api.annotation.SofaService) ComponentInfo(com.alipay.sofa.runtime.spi.component.ComponentInfo) SofaService(com.alipay.sofa.runtime.api.annotation.SofaService) Implementation(com.alipay.sofa.runtime.spi.component.Implementation) ServiceRuntimeException(com.alipay.sofa.runtime.api.ServiceRuntimeException) SpringImplementationImpl(com.alipay.sofa.runtime.spi.spring.SpringImplementationImpl) JvmBinding(com.alipay.sofa.runtime.service.binding.JvmBinding)

Aggregations

SofaService (com.alipay.sofa.runtime.api.annotation.SofaService)14 FatalBeanException (org.springframework.beans.FatalBeanException)6 BeanDefinitionBuilder (org.springframework.beans.factory.support.BeanDefinitionBuilder)6 PlaceHolderBinder (com.alipay.sofa.boot.annotation.PlaceHolderBinder)5 SofaServiceBinding (com.alipay.sofa.runtime.api.annotation.SofaServiceBinding)5 ServiceRuntimeException (com.alipay.sofa.runtime.api.ServiceRuntimeException)4 JvmBinding (com.alipay.sofa.runtime.service.binding.JvmBinding)4 BeanDefinitionRegistry (org.springframework.beans.factory.support.BeanDefinitionRegistry)4 AnnotationWrapperBuilder (com.alipay.sofa.boot.annotation.PlaceHolderAnnotationInvocationHandler.AnnotationWrapperBuilder)3 ErrorCode (com.alipay.sofa.boot.error.ErrorCode)3 BeanDefinitionUtil (com.alipay.sofa.boot.util.BeanDefinitionUtil)3 SofaReference (com.alipay.sofa.runtime.api.annotation.SofaReference)3 SofaReferenceBinding (com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding)3 BindingType (com.alipay.sofa.runtime.api.binding.BindingType)3 SofaLogger (com.alipay.sofa.runtime.log.SofaLogger)3 Binding (com.alipay.sofa.runtime.spi.binding.Binding)3 SofaRuntimeContext (com.alipay.sofa.runtime.spi.component.SofaRuntimeContext)3 BindingConverter (com.alipay.sofa.runtime.spi.service.BindingConverter)3 BindingConverterContext (com.alipay.sofa.runtime.spi.service.BindingConverterContext)3 BindingConverterFactory (com.alipay.sofa.runtime.spi.service.BindingConverterFactory)3