spring - Spring boot @Inject 代理解析为 null
问题描述
我正在重构现有应用程序以使用 Spring Boot。我在这里遇到的问题通常是“为什么这不再起作用”的类型。
我有三个包 - nl.myproject.boot - nl.myproject - nl.myproject.rest
我当前的问题是,当对它们调用方法时,我解析为 null 的所有s @Service
。服务和 dao 是 nl.myproject 包的一部分,它不是 nl.myproject.core 的原因是遗留问题。@Inject
@RESTController
一个相关的问题是我的@Configuration 组件似乎没有被加载@ComponentScan
,我必须手动导入它们。我还必须排除测试配置以防止加载测试配置,这看起来也很奇怪。
启动过程中来自服务层的内部调用,如数据准备工作正常。任何这样的经理也是@Inject
ed。这只是说任何典型的注入错误,例如手动实例化或注入类而不是接口都不适用。
我也很感激调试技巧。我的 Java 有点生锈了。
@EnableAutoConfiguration
@ComponentScan(basePackages= {
"nl.myproject",
"nl.myproject.boot",
"nl.myproject.dao",
"nl.myproject.service",
"nl.myproject.webapp"},
excludeFilters= {
@ComponentScan.Filter(type=FilterType.REGEX,pattern={".*Test.*"}),
@ComponentScan.Filter(type=FilterType.REGEX,pattern={".*AppConfig"})
}
)
@Configuration
@EnableConfigurationProperties
@Import({
JPAConfig.class,
RestConfig.class,
BootConfig.class
})
public class Startup {
public static void main(String[] args) throws Exception {
SpringApplication.run(Startup.class, args);
}
}
@RestController
@RequestMapping(value="/json/tags")
public class JsonTagController extends JsonBaseController {
@Inject
TagManager tagMgr;
public interface TagManager extends BaseManager<Tag,Long> {
[...]
}
@Service("tagManager")
public class TagManagerImpl extends BaseManagerImpl<Tag, Long> implements
TagManager {
@Inject
TagDao dao;
[...]
解决方案
@Inject
是由 JSR-330(标准) @Autowired
指定的注解,而是由Spring指定的注解。
他们只是做同样的依赖注入。您可以在同一代码中使用它们。
只是您需要的修改(关注点分离):
public interface TagManager {
[...]
}
@Service
public class TagManagerImpl implements TagManager {
@Inject
private TagDao dao;
// inject that service rather than extending
@Inject
private BaseManager<Tag,Long> baseManager;
}
public interface BaseManager<Tag,Long> {
[...]
}
@Service
public class BaseManagerImpl<Tag,Long> implements BaseManager<Tag,Long> {
....
}
您只需检查一件事,只需修改为 basePackages= {"nl.myproject"}
- 仅提供基本包,这足以让 spring 扫描每个包中的组件。
希望这可能会有所帮助:)
推荐阅读
- python - 如何修复python中graphql查询中的“解析错误(VAR_SIGN)”
- box2d - 如何在box2d中查找矩形顶部是否碰撞
- ios - 提交到使用 iOS 12.1 SDK 构建的 App Store
- ios - 快速识别来自 weburl 的资源名称和扩展名
- java - 如何在 Spring Boot 1 应用程序中查找未使用的属性
- python - Python 中基于类的 AWS lambda
- java - 使用 JDBC 在 Mysql 中更新查询的问题
- c# - 格式化 DateTime,中间有文本
- sql-server - 根据星期几控制 SP 代码流
- azure - adfs 和 azure AD 的区别