java - 这相当于在 XML 配置文件中使用 @Autowire 注释 Autowiring 接口(interface)?

标签 java xml spring spring-java-config xml-configuration

我发现使用 @Autowire 注释注入(inject) 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时,你实际上是在按类型进行 Autowiring 。 @Autowire 只是注入(inject) shopRepo bean 的实现。 shopRepo 的实现是由 jpa 存储库动态实例化的,通常是在 spring 容器启动期间。

您的 xml 配置没有按类型进行任何 Autowiring ,它正在尝试将 id 为“shopRepo”的 bean 注入(inject)到 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>

关于java - 这相当于在 XML 配置文件中使用 @Autowire 注释 Autowiring 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50758080/

相关文章:

java - 在用户输入后更改 Java for Android 中形状的颜色

java - 如何在 Spring boot 中手动配置 SSL 握手

sql - 在 Spring Boot 中创建原生 SQL 查询而不创建实体类

java - Activity 占用大量内存,如何减少?

c++ - 使用 Xerces-C++ 解析递归 XML 模式 (XSD) 时出现段错误

java - 我如何从 URL 下载并保存设备存储 "Pdf file"单击 RecyclerView?

java - 嵌套元素列表的 JAXB 注释

java - 如何在 Spring Boot 中处理最大文件大小异常?

java - 如何根据已过去的时间更改 Java 中哈希表内的值?

java - Webdriver 抛出 "Cannot navigate to invalid URL"错误