【发布时间】:2021-01-20 06:05:00
【问题描述】:
我正在尝试使用属性占位符值来定义服务 bean 名称。但是得到错误说没有找到特定名称的bean。我知道问题在于读取属性值,因为在硬编码值时它正在工作。请帮忙,因为我需要从属性文件中读取值。代码如下:sn-p:
application.properties
event.testRequest=TEST_REQUEST
服务类
@Service("${event.testRequest}") // This is not working, getting "No bean named 'TEST_REQUEST' available" error
// @Service("TEST_REQUEST") // This is working
public class TestRequestExecutor extends DefaultExecutionService {
...
}
另外,为了确认属性值读取正确,我尝试使用@Value("${event.testRequest}") private String value,我得到了预期的值“TEST_REQUEST”。不确定如何将其与 @Service 注释一起使用。
编辑: 为了详细说明将服务 bean 名称外部化的需要,我使用工厂模式来获取基于事件名称(事件名称,例如 Event1、Event2..)的实现。如果事件名称发生更改,则更改将仅发生在属性文件上,而不是使用属性占位符的服务 bean 名称。
@RestController
public class RequestProcessController {
@Autowired
private ExecutorFactory executorFactory;
..
ExecutionService executionService = executorFactory.getExecutionService(request.getEventType());
executionService.executeRequest(request);
..
}
@Component
public class ExecutorFactory {
private BeanFactory beanFactory;
public ExecutionService getExecutionService(String eventType) {
return beanFactory.getBean(eventType, DefaultExecutionService.class);
}
这里DefaultExecutionService 有不同的实现,如下所示..
@Service("${event.first}")
public class Event1Executor extends DefaultExecutionService {..}
..
@Service("${event.second}")
public class Event2Executor extends DefaultExecutionService {..}
event.first = Event1
event.second = Event2
所以基本上以后如果Event1名称更新为EventOne,我只需要更新属性文件,而不是服务类。
非常感谢任何帮助!谢谢!
【问题讨论】:
-
您不能在
@Component注释中使用占位符(@Service就是其中之一)`。在我的书中动态分配名称也没有任何意义。 -
你能详细说明为什么你真的需要这样做吗?为了正确的依赖注入解析规则,spring 需要引用 spring bean 的名称。我从来没有看到需要让它们动态化。我相信如果你能提出问题,还有其他方法可以解决这个问题......
-
@MarkBramnik 我们有不同的实现。我们需要将其外部化以从属性文件中读取,因为每个占位符的名称(这些是事件名称)将来可能会有所不同,并且它将在属性文件中更新。因此,无需更改代码,我们仍然可以使用现有代码,因为服务正在引用属性值。希望清楚。
-
不是很清楚,所以你有不同的 DefaultExecutionService 实现,对吧?假设它可以工作,你在哪里使用解析的bean名称,我的意思是,如果spring能够从配置文件中解析@Service(“someService”)或@Service(“anotherService”),你在哪里使用字符串“someService ”或“另一个服务”在应用程序中?如果您只需要加载许多实现中的一种,则可以使用 \@ConditionalOnProperty 代替,在某些其他情况下,使用 \@Profile 可能很方便(虽然在引擎盖下是相同的),但它与您的技术不同问...
-
@MarkBramnik 请查看我帖子中的编辑部分。我已经详细解释过了。如果还不清楚,请告诉我。
标签: spring-boot property-placeholder