Spring: 根据配置文件选择@Service

Spring: Selecting @Service based on profile

我有一个接口定义如下:

public interface MyService {
}

还有两个 类 实施它:

@Service
@Profile("dev")
public class DevImplementation implements MyService {
}

@Service
@Profile("prod")
public class ProdImplementation implements MyService {
}

还有另一个服务正在尝试使用它:

@Service
public MyClass {
    @Autowired
    MyService myservice;
}

问题是我在 运行 编译代码时得到 NoSuchBeanException。 运行 使用

mvn spring-boot:run -P dev

我做错了什么?

使用 -P 启用 Maven 配置文件。但是 Maven 配置文件独立于 Spring 配置文件。只要您没有配置 Maven 配置文件来设置适当的 Spring 属性,您就必须以这种方式启用 Spring 配置文件:

mvn spring-boot:run -Dspring.profiles.active=dev

实现此目的的另一种方法是拥有一个生产配置文件,并且开发是隐含的,而不是被设置,例如

@Component
@Profile("prod")
public class ProdImplementation implements MyService {
}

...开发人员实现的配置文件为“!prod”。

@Component
@Profile("!prod")
public class DevImplementation implements MyService {
}

所以要 运行 在生产模式下,您必须键入配置文件 ...

> mvn spring-boot:run -Dspring.profiles.active=prod

...并且开发模式不需要配置文件...

> mvn spring-boot:run

IMO 更容易一些。