首页 > 解决方案 > 哪个相当于在 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>

标签: javaxmlspringspring-java-configxml-configuration

解决方案


当您使用@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>

推荐阅读