java Spring在运行时选择bean实现

arknldoa  于 2023-05-05  发布在  Java
关注(0)|答案(8)|浏览(120)

我正在使用带注解的SpringBeans,我需要在运行时选择不同的实现。

@Service
public class MyService {
   public void test(){...}
}

例如,对于windows平台,我需要MyServiceWin extending MyService,对于linux平台,我需要MyServiceLnx extending MyService
现在我只知道一个可怕的解决办法:

@Service
public class MyService {

    private MyService impl;

   @PostInit
   public void init(){
        if(windows) impl=new MyServiceWin();
        else impl=new MyServiceLnx();
   }

   public void test(){
        impl.test();
   }
}

请考虑我只使用注解而不是XML配置。

zhte4eai

zhte4eai1#

1.实现自定义Condition

public class LinuxCondition implements Condition {
  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    return context.getEnvironment().getProperty("os.name").contains("Linux");  }
}

对于Windows也是如此。

2.在Configuration类中使用@Conditional

@Configuration
public class MyConfiguration {
   @Bean
   @Conditional(LinuxCondition.class)
   public MyService getMyLinuxService() {
      return new LinuxService();
   }

   @Bean
   @Conditional(WindowsCondition.class)
   public MyService getMyWindowsService() {
      return new WindowsService();
   }
}

3.照常使用@Autowired

@Service
public class SomeOtherServiceUsingMyService {

    @Autowired    
    private MyService impl;

    // ... 
}
rks48beu

rks48beu2#

您可以将bean注入移动到配置中,如下所示:

@Configuration
public class AppConfig {

    @Bean
    public MyService getMyService() {
        if(windows) return new MyServiceWin();
        else return new MyServiceLnx();
    }
}

或者,您可以使用windowslinux配置文件,然后使用@Profile注解您的服务实现,如@Profile("linux")@Profile("windows"),并为您的应用程序提供其中一个配置文件。

djmepvbi

djmepvbi3#

让我们创建一个漂亮的配置。
假设我们有Animal接口,我们有DogCat实现。我们想写写:

@Autowired
Animal animal;

但是我们应该返回哪个实现呢?

那么什么是解决方案呢?解决问题有很多方法。我会写如何一起使用**@Qualifier**和自定义条件。
首先,让我们创建我们的自定义注解:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
public @interface AnimalType {
    String value() default "";
}

配置:

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class AnimalFactoryConfig {

    @Bean(name = "AnimalBean")
    @AnimalType("Dog")
    @Conditional(AnimalCondition.class)
    public Animal getDog() {
        return new Dog();
    }

    @Bean(name = "AnimalBean")
    @AnimalType("Cat")
    @Conditional(AnimalCondition.class)
    public Animal getCat() {
        return new Cat();
    }

}

注意我们的bean名称为AnimalBean为什么我们需要这个bean?因为当我们注入Animal接口时,我们只需要写@Qualifier(“AnimalBean”)

另外,我们创建了自定义注解来将值传递给我们的自定义条件
现在我们的条件看起来像这样(假设“Dog”名称来自配置文件或JVM参数或...)

public class AnimalCondition implements Condition {

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        if (annotatedTypeMetadata.isAnnotated(AnimalType.class.getCanonicalName())){
           return annotatedTypeMetadata.getAnnotationAttributes(AnimalType.class.getCanonicalName())
                   .entrySet().stream().anyMatch(f -> f.getValue().equals("Dog"));
        }
        return false;
    }
}

最后注射:

@Qualifier("AnimalBean")
@Autowired
Animal animal;
wbgh16ku

wbgh16ku4#

将所有实现自动连接到带有@Qualifier注解的工厂中,然后从工厂返回所需的服务类。

public class MyService {
    private void doStuff();
}

我的Windows服务:

@Service("myWindowsService")
public class MyWindowsService implements MyService {

    @Override
    private void doStuff() {
        //Windows specific stuff happens here.
    }
}

我的Mac服务:

@Service("myMacService")
public class MyMacService implements MyService {

    @Override
    private void doStuff() {
        //Mac specific stuff happens here
    }
}

我的工厂:

@Component
public class MyFactory {
    @Autowired
    @Qualifier("myWindowsService")
    private MyService windowsService;

    @Autowired
    @Qualifier("myMacService")
    private MyService macService;

    public MyService getService(String serviceNeeded){
        //This logic is ugly
        if(serviceNeeded == "Windows"){
            return windowsService;
        } else {
            return macService;
        }
    }
}

如果你真的想玩点花样,你可以使用枚举来存储你的实现类类型,然后使用枚举值来选择你想要返回的实现。

public enum ServiceStore {
    MAC("myMacService", MyMacService.class),
    WINDOWS("myWindowsService", MyWindowsService.class);

    private String serviceName;
    private Class<?> clazz;

    private static final Map<Class<?>, ServiceStore> mapOfClassTypes = new HashMap<Class<?>, ServiceStore>();

    static {
        //This little bit of black magic, basically sets up your 
        //static map and allows you to get an enum value based on a classtype
        ServiceStore[] namesArray = ServiceStore.values();
        for(ServiceStore name : namesArray){
            mapOfClassTypes.put(name.getClassType, name);
        }
    }

    private ServiceStore(String serviceName, Class<?> clazz){
        this.serviceName = serviceName;
        this.clazz = clazz;
    }

    public String getServiceBeanName() {
        return serviceName;
    }

    public static <T> ServiceStore getOrdinalFromValue(Class<?> clazz) {
        return mapOfClassTypes.get(clazz);
    }
}

然后,您的工厂可以进入应用程序上下文并将示例拉入它自己的Map中。当您添加一个新的服务类时,只需向枚举中添加另一个条目,这就是您所要做的全部工作。

public class ServiceFactory implements ApplicationContextAware {

     private final Map<String, MyService> myServices = new Hashmap<String, MyService>();

     public MyService getInstance(Class<?> clazz) {
         return myServices.get(ServiceStore.getOrdinalFromValue(clazz).getServiceName());
     }

      public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
          myServices.putAll(applicationContext.getBeansofType(MyService.class));
      }
 }

现在,您可以将所需的类类型传递到工厂中,它将为您提供所需的示例。非常有帮助,特别是如果你想使服务通用。

snz8szmq

snz8szmq5#

只需将@Service注解的类设置为条件:**仅此而已。**不需要其他显式的@Bean方法。

public enum Implementation {
    FOO, BAR
}

@Configuration
public class FooCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Implementation implementation = Implementation.valueOf(context.getEnvironment().getProperty("implementation"));
        return Implementation.FOO == implementation;
    }
}

@Configuration
public class BarCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Implementation implementation = Implementation.valueOf(context.getEnvironment().getProperty("implementation"));
        return Implementation.BAR == implementation;
    }
}

奇迹发生了。条件是正确的,它属于:在实现类。

@Conditional(FooCondition.class)
@Service
class MyServiceFooImpl implements MyService {
    // ...
}

@Conditional(BarCondition.class)
@Service
class MyServiceBarImpl implements MyService {
    // ...
}

然后,您可以像往常一样使用Dependency Injection,例如通过Lombok@RequiredArgsConstructor@Autowired

@Service
@RequiredArgsConstructor
public class MyApp {
    private final MyService myService;
    // ...
}

把它放到你的应用程序中。yml:

implementation: FOO

👍仅示例化带有FooCondition**注解的实现。无幻像示例化。**👍

relj7zay

relj7zay6#

我只是在这个问题上加了两分钱。请注意,不必像其他答案所显示的那样实现那么多java类。可以简单地使用@ConditionalOnProperty。示例:

@Service
@ConditionalOnProperty(
  value="property.my.service", 
  havingValue = "foo", 
  matchIfMissing = true)
class MyServiceFooImpl implements MyService {
    // ...
}

@ConditionalOnProperty(
  value="property.my.service", 
  havingValue = "bar")
class MyServiceBarImpl implements MyService {
    // ...
}

把它放到你的应用程序中。yml:

property.my.service: foo
q0qdq0h2

q0qdq0h27#

MyService.java:

public interface MyService {
  String message();
}

MyServiceConfig.java:

@Configuration
public class MyServiceConfig {

  @Value("${service-type}")
  MyServiceTypes myServiceType;

  @Bean
  public MyService getMyService() {
    if (myServiceType == MyServiceTypes.One) {
      return new MyServiceImp1();
    } else {
      return new MyServiceImp2();
    }
  }
}

application.properties:

service-type=one

MyServiceTypes.java

public enum MyServiceTypes {
  One,
  Two
}

在任何Bean/组件/服务等中使用例如:

@Autowired
    MyService myService;
    ...
    String message = myService.message()
ijxebb2r

ijxebb2r8#

AOP(AspectJ)解决方案

@AutowiredCustom
public SpeedLimitService speedLimitService;

方面:

import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import performance.context.CountryHolder;

import java.lang.reflect.Field;

/**
 */
@Aspect
@Component
public aspect AutowiredCustomFieldAspect implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    pointcut annotatedField(): get(@performance.annotation.AutowiredCustom * *);

    before(Object object): annotatedField() && target(object) {
        try {
            String fieldName = thisJoinPoint.getSignature().getName();
            Field field = object.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);

            String className = field.getType().getSimpleName() + CountryHolder.getCountry().name();

            Object bean = applicationContext.getAutowireCapableBeanFactory().getBean(className);

            field.set(object, bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

}

豆子:

@Service("SpeedLimitServiceCH")
public class SpeedLimitServiceCH implements SpeedLimitService {

    @Override
    public int getHighwaySpeedLimit() {
        return 120;
    }
}

@Service("SpeedLimitServiceDE")
public class SpeedLimitServiceDE implements SpeedLimitService {

    @Override
    public int getHighwaySpeedLimit() {
        return 200;
    }
}

pom.xml配置

...
                 <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>aspectj-maven-plugin</artifactId>
                    <version>${aspectj-maven-plugin.version}</version>
                    <configuration>
                        <complianceLevel>${java.version}</complianceLevel>
                        <source>${maven.compiler.source}</source>
                        <target>${maven.compiler.target}</target>
                        <showWeaveInfo>true</showWeaveInfo>
                        <verbose>true</verbose>
                        <Xlint>ignore</Xlint>
                        <encoding>${project.build.sourceEncoding}</encoding>
                    </configuration>
                    <executions>
                        <execution>
                            <goals>
                                <!-- use this goal to weave all your main classes -->
                                <goal>compile</goal>
                                <!-- use this goal to weave all your test classes -->
                                <goal>test-compile</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
    
            </plugins>
        </build>
    </project>

参考:

https://viktorreinok.medium.com/dependency-injection-pattern-for-cleaner-business-logic-in-your-java-spring-application-f4ace0a3cba7

相关问题