我可以在主类中成功读取HandlerSettings的自动装配实例,所以我知道我的application.properties条目是正确的。
@Component
@ConfigurationProperties(prefix="handler")
public class HandlerSettings {
private int timeout;
public int getTimeout(){
return timeout;
}
public void setTimeout(int timeout){
this.timeout = timeout;
}
}
我在MyHandler类中尝试自动装配字段时遇到了困难,MyHandler类在PerConnectionWebSocketHandler中实例化。
@SpringBootApplication
@RestController
@EnableWebSocket
@EnableConfigurationProperties(HandlerSettings.class)
public class MyController implements WebSocketConfigurer{
@Bean
public WebSocketHandler myHandler() {
return new PerConnectionWebSocketHandler(MyHandler.class));
}
我想在MyHandler的抽象基类中自动装配字段。
@Component
public abstract class Handler implements WebSocketHandler {
@Autowired
private HandlerSettings handlerSettings;
...
}
MyHandler继承自Handler:
public class MyHandler extends Handler
Spring documentation中的示例没有说明在继承的情况下要做什么,或者使用PerConnectionWebSocketHandler实例化类的方式。
我尝试在Handler中自动装配字段失败了。如果类是由PerConnectionWebSocketHandler实例化的话,可以自动装配吗?如果是这样,我是否需要做一些特殊的自动装配基类,而不是扩展它的类?
答案 0 :(得分:1)
根据源代码,除非您设置PerConnectionWebSocketHandler.setBeanFactory
in将在没有Injected Beans的情况下实例化Handler。
@SpringBootApplication
@RestController
@EnableWebSocket
@EnableConfigurationProperties(HandlerSettings.class)
public class MyController implements WebSocketConfigurer {
@Autowired
private BeanFactory beanFactory;
@Bean
public WebSocketHandler myHandler() {
PerConnectionWebSocketHandler perConnectionWebSocketHandler = new PerConnectionWebSocketHandler(MyHandler.class);
perConnectionWebSocketHandler.setBeanFactory(beanFactory);
return perConnectionWebSocketHandler;
}
}