java - 哪个相当于在 XML 配置文件中使用 @Autowire 注释自动装配接口?
问题描述
我看到使用 @Autowire 注释注入 ShopRepo 是有效的,但是当我尝试使用 xml 执行此操作时,有时它会起作用,有时则不起作用(另外,intellij 说我不能使用抽象 bean 作为属性)。为什么它与注释一起使用并且与 xml 配置一起工作并不总是有效(这是不同的)?我怎样才能使它与 xml 配置一起工作?
代码如下所示:
public interface ShopRepo extends JpaRepository<Product, Long> {
@Override
Optional<Product> findById(Long aLong);
}
public class ShopController {
//@Autowired
private ShopRepo shopRepo;
public void setShopRepo(ShopRepo shopRepo) {
this.shopRepo = shopRepo;
}
public Product findProduct(Long id) {
return shopRepo.findById(1l).orElse(new Product());
}
}
<jpa:repositories base-package="com.example.shop.repository"/>
<bean id="shopRepo" class="com.example.shop.repository.ShopRepo" abstract="true"/>
<bean id="shopController" class="com.example.shop.controller.ShopController">
<property name="shopRepo" ref="shopRepo"/>
</bean>
解决方案
当您使用@Autowire 时,您实际上是在按类型进行自动装配。@Autowire 只是注入了 shopRepo bean 的实现。shopRepo 的实现由 jpa 存储库动态实例化,通常在 spring 容器启动期间。
您的 xml 配置没有按类型进行任何自动装配,它正在尝试将 id 为“shopRepo”的 bean 注入到 shopcontroller bean 中。您的 xml 中的 shopRepo 定义只是一个定义,而不是 jpa 存储库创建的实际实现的名称。
您可以在您的 xml 文件中执行此操作。希望这可以帮助。
<bean id="shopRepo" class="com.example.shop.repository.ShopRepo" abstract="true"/>
<bean id="shopController" class="com.example.shop.controller.ShopController" autowire="byType">
</bean>
推荐阅读
- couchbase - 打开存储桶时出错#bucket:无法连接到任何指定的主机(使用 x.509 证书将网关身份验证同步到 Couchbase。)
- sql - 如何删除表中具有空外键引用的所有行?
- c# - 尝试合计支付金额时显示错误值的总和
- ios - 在 xcode11 中为 ios13 获取错误的用户当前位置
- windows-subsystem-for-linux - 无法从 Windows 访问在 WSL2 上运行的 Artemis
- gstreamer - Gstreamer:使用 qtmux 的 moov-recovery 信息?
- css - 在设备尺寸上集中对齐项目 =< 小
- c# - 通过 httpclient 在 Polly 库中使用指数退避
- reactjs - 有没有办法在图表中显示 x 轴参考线直到特定 y 轴值?
- javascript - Yii2-通过jquery在按钮单击时向文本输入字段插入值