1

私はこの状況を持っています: すべてのサービス インターフェイスを集約する 1 つのインターフェイス サービスがあります。たとえば、ILoginService1 と ILoginService2 の 2 つのインターフェイスがある場合、Service インターフェイスは次のようになります。

Service extends ILoginService1,ILoginService2. 

次のような特定のコンテキストでこのインターフェイスにアクセスできるようにする必要があります。

service.login();

これが私の解決策です( http://artofsoftwarereuse.com/tag/dynamic-proxy/に似たもの):

Service インターフェイスに配置する 1 つの注釈 ServiceFacade を作成し、Service インターフェイスの DynamicProxy を作成する BeanPostProcessor を用意します。しかし、問題は、@Component を配置した場合でも、Spring コンポーネント スキャンから Service インターフェイスが取得されず、他のコンポーネントが Spring コンテナーに配置されることです。

これまでの解決策を修正するにはどうすればよいですか、何か不足していますか、または他の解決策はありますか? ソースコードは次のとおりです: applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config/>    
    <context:component-scan base-package="org.finki.auction.ui.application"/>
    <context:component-scan base-package="org.finki.auction.services"/>

</beans>

注釈:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceFacade{}

動的プロキシの呼び出しハンドラ:

/**
 * 
 */
package org.finki.auction.services;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * 
 */
@Component("serviceLayer")
public class ServiceLayer implements InvocationHandler, ApplicationContextAware
{

    private static ApplicationContext applicationContext = null;
    private static Map<String, String> serviceMap = new HashMap<>();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
    {
        Object result;
        try
        {
            String searchKey = method.getName();
            String beanName = serviceMap.get(searchKey);
            Object methodObject = applicationContext.getBean(beanName);
            result = method.invoke(methodObject, args);
        } catch (InvocationTargetException e)
        {
            throw e.getTargetException();
        } catch (Exception e)
        {
            throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
        }
        return result;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        ServiceLayer.applicationContext = applicationContext;

        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(Service.class);
        for (Map.Entry<String, Object> entryBean : beans.entrySet())
        {
            String beanName = entryBean.getKey();
            Object beanObject = entryBean.getValue();
            Method[] beanMethods = beanObject.getClass().getDeclaredMethods();
            for (Method bMethod : beanMethods)
            {
                serviceMap.put(bMethod.getName(), beanName);
            }
        }
    }

}

BeanPostProcessor クラス:

/**
 * 
 */
package org.finki.auction.services.annotation;

import java.lang.reflect.Proxy;
import java.util.Arrays;

import org.finki.auction.services.Service;
import org.finki.auction.services.ServiceLayer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 
 */
@Component("serviceFacadeProcessor")
public class ServiceFacadeProcessor implements BeanPostProcessor, ApplicationContextAware
{

    private static ApplicationContext applicationContext = null;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException
    {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException
    {
        Class<?> clz = bean.getClass();
        Class<?>[] tmpInterfaces = clz.getInterfaces();
        System.out.println("ServiceFacadeProcessor : " + bean);
        if (tmpInterfaces != null && tmpInterfaces.length == 1
                && tmpInterfaces[0].isAnnotationPresent(ServiceFacade.class))
        {

            System.out.println("Find serviceFacade >>>>");
            Class<?>[] interfaces = Arrays.copyOf(tmpInterfaces, tmpInterfaces.length + 1);

            interfaces[tmpInterfaces.length] = Service.class;
            ClassLoader cl = bean.getClass().getClassLoader();
            ServiceLayer serviceLayerBean = applicationContext.getBean("serviceLayer", ServiceLayer.class);
            Object t = Proxy.newProxyInstance(cl, interfaces, serviceLayerBean);
            System.out.println("Find serviceFacade <<<<");
            return t;
        }

        return bean;

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        ServiceFacadeProcessor.applicationContext = applicationContext;
    }

}

したがって、私の問題は構成ではありません。私の問題は、BeanPostProcessor によってキャッチされ、動的プロキシを作成するために、サービス インターフェイスをスプリング コンテナーにアタッチする方法です。これまでのところ、何かが足りないかもしれませんが、誰かがそれを行うより良い方法を持っている場合は、今すぐ許可してください。前もって感謝します

解決:

/**
 * 
 */
package org.finki.auction.services.annotation;

import java.lang.reflect.Proxy;
import java.util.Arrays;

import org.finki.auction.services.Service;
import org.finki.auction.services.ServiceLayer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author
 * 
 */
@Component
public class ServiceFactoryBean implements FactoryBean<Service>, ApplicationContextAware
{

    private static ApplicationContext applicationContext = null;

    @Override
    public Service getObject() throws Exception
    {

        Class<?>[] tmpInterfaces = Service.class.getInterfaces();
        Class<?>[] interfaces = Arrays.copyOf(tmpInterfaces, tmpInterfaces.length + 1);
        interfaces[tmpInterfaces.length] = Service.class;
        ServiceLayer serviceLayerBean = applicationContext.getBean("serviceLayer", ServiceLayer.class);
        ClassLoader cl = serviceLayerBean.getClass().getClassLoader();
        Object t = Proxy.newProxyInstance(cl, interfaces, serviceLayerBean);
        return (Service) t;
    }

    @Override
    public Class<?> getObjectType()
    {
        return Service.class;
    }

    @Override
    public boolean isSingleton()
    {
        return true;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
    {
        ServiceFactoryBean.applicationContext = applicationContext;
    }

}

BeanPostProcessor とアノテーションも削除する必要があります。

4

1 に答える 1

3

私は似たようなことに遭遇し、Spring の Java 構成機能を使用してシナリオを機能させることができると信じています。

@Configuration
public class ServiceConfiguration {

    // you can wire your service1 and service2 here

    @Bean
    Service service() {
         // create and return dynamic proxy here
    }
}

このようにして、タイプが「サービス」で名前が「サービス」の Bean になり、呼び出しハンドラーなどを備えた動的プロキシになります。

Java構成は、上記で概説したアプローチ(service1とservice2を構成に配線する場所)に限定されないと確信しています-これは実装の詳細だと思います。

于 2013-05-07T14:17:45.990 に答える