我正在尝试在@Service
类中@Autowire
一个@Configuration
类。基本上,我的@Configuration
类包含到我的自定义.properties
文件的映射。当我尝试在服务类中自动连接配置类时,会出现BeanCreationException
。我不确定会发生什么。刚刚遵循了关于从spring创建属性类的指南。我一定错过了什么。
此外,当我尝试将@Configuration
类自动连接到另一个@Configuration
类时,它会顺利运行
目前,我知道prop
总是空的,因为当我删除prop.getUploadFileLocation()
调用时,一切都会好起来。自动布线时一定出了问题。
这是我的服务类
@Service
public class ImageService {
public static Logger logger = Logger.getLogger(ImageService.class.getName());
@Autowired
MyProperties prop;
private final String FILE_UPLOAD_LOCATION = prop.getUploadFileLocation() +"uploads/images/";
public void upload(String base64ImageFIle) throws IOException {
logger.info(FILE_UPLOAD_LOCATION);
}
}
这是我的配置类
@Data
@Configuration
@ConfigurationProperties (prefix = "my")
public class MyProperties {
private String resourceLocation;
private String resourceUrl;
public String getUploadFileLocation() {
return getResourceLocation().replace("file:///", "");
}
public String getBaseResourceUrl() {
return getResourceUrl().replace("**", "");
}
}
这里是我可以成功使用MyProperties
的地方
@Configuration
public class StaticResourceConfiguration implements WebMvcConfigurer {
@Autowired
MyProperties prop;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(prop.getResourceUrl())
.addResourceLocations(prop.getResourceLocation());
}
}
问题是您试图使用自动连接字段来设置内联字段分配中的值。
这意味着
private final String FILE_UPLOAD_LOCATION = prop.getUploadFileLocation() +"uploads/images/";
在prop
自动连线之前执行,这意味着它将始终为空
缓解这种情况的方法是使用构造函数注入。
@Service
public class ImageService {
//Fine since you are using static method
public static Logger logger = Logger.getLogger(ImageService.class.getName());
//Not needed if you are only using it to set FILE_UPLOAD_LOCATION
//Allows field to be final
private final MyProperties prop;
//Still final
private final String FILE_UPLOAD_LOCATION;
//No need for @Autowired since implicit on component constructors
ImageService(MyProperties prop){
//Again not needed if you aren't going to use anywhere else in the class
this.prop = prop;
FILE_UPLOAD_LOCATION = prop.getUploadFileLocation() +"uploads/images/";
}
public void upload(String base64ImageFIle) throws IOException {
logger.info(FILE_UPLOAD_LOCATION);
}
}
请参阅这个问题,了解为什么在一般中构造函数比@autowired更受欢迎
如果您需要在StaticResourceConfiguration
bean之前创建MyProperties
bean,您可以按如下方式放置@ConditionalOnBean(MyProperties.class)
。Spring将在处理StaticResourceConfiguration
之前确保存在MyProperties
。
@Configuration
@ConditionalOnBean(MyProperties.class)
public class StaticResourceConfiguration implements WebMvcConfigurer {