如何为Spring非托管类OverlayServiceImpl注入依赖?
解决非托管类OverlayServiceImpl的依赖注入问题
核心问题原因
你通过new OverlayServiceImpl()手动创建实例,即便类上标注了@Configurable,Spring默认也无法对这种手动实例化的对象做依赖注入——@Configurable的生效依赖AspectJ的织入机制,用来增强new关键字创建对象的过程,让Spring能介入完成注入。
具体解决步骤
1. 修正注解配置
- 移除
OverlayServiceImpl上的@EnableSpringConfigured注解,这个注解应该放在Spring的配置类(带@Configuration的类)中,而非非托管类上。 - 调整
@Configurable的注入模式,建议使用BY_TYPE更贴合Spring常规注入逻辑,或者保留BY_NAME但确保Bean名称匹配:@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE) public class OverlayServiceImpl implements GenericVehicleOverlayService<T, R> { @Autowired AbstractLayoutProperties layoutProperties; public void findOnlyActive(){ String appName = layoutProperties.getAppName(); } }
2. 启用AspectJ织入
- 在Spring配置类中添加
@EnableSpringConfigured和@EnableLoadTimeWeaving以开启运行期织入:@Configuration @EnableSpringConfigured @EnableLoadTimeWeaving public class SpringConfig { // 其他配置内容 } - 引入spring-instrument依赖,并添加JVM启动参数:
JVM启动参数需添加:<!-- Maven依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument</artifactId> <version>${spring.version}</version> <scope>provided</scope> </dependency>-javaagent:path/to/spring-instrument-{version}.jar(替换为实际的jar路径)
3. 替代方案:避免手动new对象(更推荐)
如果不想依赖AspectJ织入,可以改用Spring托管的方式:
- 给
OverlayServiceImpl添加@Service或@Component注解,转为Spring托管Bean,然后在OtherService中注入使用:@Service public class OverlayServiceImpl implements GenericVehicleOverlayService<T, R> { @Autowired AbstractLayoutProperties layoutProperties; public void findOnlyActive(){ String appName = layoutProperties.getAppName(); } } @Service public class OtherService{ @Autowired private OverlayServiceImpl overlayService; public void findActive(){ overlayService.findOnlyActive(); } @Autowired OtherRepository otherRepo; } - 若必须手动创建实例,可通过Spring容器手动触发注入:
@Service public class OtherService{ @Autowired private ApplicationContext context; public void findActive(){ OverlayServiceImpl impl = new OverlayServiceImpl(); context.getAutowireCapableBeanFactory().autowireBean(impl); impl.findOnlyActive(); } @Autowired OtherRepository otherRepo; }
4. 基础验证
- 确认
AbstractLayoutProperties所在包被Spring扫描覆盖,确保它已被实例化为Bean。 - 检查
S3Service和S3Client本身也是Spring托管Bean,避免因它们未被注入导致连锁空指针。
内容的提问来源于stack exchange,提问作者jack
相关产品推荐
相关产品推荐

