@Autowired使用错误的实现,尽管@ConditionalOnProperty

时间:2017-12-31 22:52:31

标签: java spring-boot dependency-injection

我按照我在网上找到的教程,使用db.mycollection.aggregate([ { $project: { child_id: '$parent.child.child_id', timestamp: '$parent.child.timestamp' }}, { $group: { cid: '$child_id', ts: { $max: '$timestmap'} }}, { $out : 'mycollectiongrouped'} ])) @ConditionalOnProperty来选择@Bean的实施。

为了完整性(虽然它与问题无关),其目的是选择一个" ICE服务器列表" provider - 在配置文件中本地配置或使用Twilio API获取WebRTC的STUN和TURN服务器列表。

以下是相关代码:

@Autowired

application.properties

ice.provider = twilio

Controller.java

@ComponentScan @RestController @EnableAutoConfiguration @EnableWebSocket public class Controller { @Autowired private IceProvider iceProvider; @Bean @ConditionalOnProperty(name = "ice.provider", havingValue = "local") public IceProvider localIceProvider() { logger.info("Creating ICE server provider - LOCAL"); return new LocalIceProvider(); } @Bean @ConditionalOnProperty(name = "ice.provider", havingValue = "twilio") public IceProvider twilioIceProvider() { logger.info("Creating ICE server provider - TWILIO"); return new TwilioIceProvider(); } }

IceProvider.java

public interface IceProvider { List<ICEServer> getIceServers(String username); }

LocalIceProvider.java

@Component public class LocalIceProvider implements IceProvider { private final static Logger logger = Logger.getLogger(LocalIceProvider.class); @PostConstruct void init() { logger.info("Reading local ICE Server list config file"); // ... } @Override public List<ICEServer> getIceServers(String username) { logger.info("Returning locally configured ICE servers"); // ... } }

TwilioIceProvider.java

尽管@Component public class TwilioIceProvider implements IceProvider { private final static Logger logger = Logger.getLogger(TwilioIceProvider.class); @Override public List<ICEServer> getIceServers(String username) { logger.info("Doing Twilio API call and returning result"); // ... } } 设置使用application.properties提供程序,但应用程序正在使用twilio提供程序。但是,正在调用local工厂方法,而不是twilioIceProvider方法。

以下是日志的摘录:

在应用程序启动时

调用localIceProvider的{​​{1}}方法和@PostConstruct的工厂方法,但不调用LocalIceProvider的工厂方法

TwilioIceProvider

根据来自调用LocalIceProvider

的客户端的请求
...
[2017-12-31 21:11:53 INFO ] [localhost-startStop-1] [ice.LocalIceProvider] Reading local ICE Server list config file
...
[2017-12-31 21:11:55 INFO ] [main] [com.example.Controller] Creating ICE server provider - TWILIO
...

由于只有iceProvider.getIceServers()工厂方法被称为[2017-12-31 21:14:40 INFO ] [http-nio-9083-exec-5] [ice.LocalIceProvider] Returning locally configured ICE servers 方法不是,为什么twilioIceProviderlocalIceProvider?< / p>

1 个答案:

答案 0 :(得分:1)

@Component实施中删除IceProvider注释。您已经在bean定义方法上使用@Bean将它们声明为bean。