java - @Autowire如何在不使用@Bean注解的情况下获取spring bean

标签 java spring spring-boot jpa

我在 springboot 项目上创建了一个 JPA 类:-

package com.example.demo.jpa;

import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.model.Users;

@Repository
public interface AppRepo extends CrudRepository<Users, Integer>, AppRepoCustom {

    public List<Users> findAllByJob(String job);

}

另一个AppRepoCustom接口(interface)是这样的:

package com.example.demo.jpa;

import java.util.List;

public interface AppRepoCustom {
    public List<String> getAllNames();

}

接口(interface)的实现:-

package com.example.demo.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.example.demo.model.Users;

public class AppRepoCustomImpl implements AppRepoCustom {

    @PersistenceContext
    EntityManager entityManager;

    @Override
    public List<String> getAllNames() {
        Query query = entityManager.createNativeQuery("SELECT name FROM springbootdb.Users as em ", Users.class);
        return query.getResultList();
    }

}

现在在我的 Controller 类中,我正在注入(inject) AppRepo 对象

@Autowired
AppRepo appRepo;

我的问题是我没有在任何地方指定要注入(inject)的 AppRepo 的实现,那么 spring 如何能够在没有任何错误的情况下注入(inject)它? 当我们创建一个接口(interface)类型的对象时,例如 Interface objectName = new implClass();其中 implClass 包含接口(interface)方法的所有实现。但是在上面的示例中,一些实现位于 CrudRepository 类中,一些实现位于 AppRepoCustom 中,那么这里的对象创建是如何进行的呢?我很困惑。当我们创建像 Interface objectName = new implClass(); 这样的对象时,以及在给定的场景中,内部对象是如何创建的。

最佳答案

如果您@Autowired AppRepoCustom,则会产生歧义。但在您的情况下,您有 @Autowired AppRepo 它是 AppRepoCustom 接口(interface)的子项。所以Spring知道你要求提供子接口(interface)的bean并提供它而没有错误。

至于在 AppRepo 的情况下将 Autowiring 哪个具体实现,请参阅 Spring 文档中的以下引用。

In this case we instruct Spring to scan com.acme.repositories and all its sub packages for interfaces extending Repository or one of its sub-interfaces. For each interface found it will register the persistence technology specific FactoryBean to create the according proxies that handle invocations of the query methods.

了解更多详情read documentation .

关于java - @Autowire如何在不使用@Bean注解的情况下获取spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58267800/

相关文章:

java - 在 TestNG 中运行时,即使对于内置类型,使用反射创建类也会抛出 java.lang.ClassNotFoundException

java - JPA Criteria OneToMany 相同实体类型过滤条件

java - 同步的 java 代码执行速度比非同步代码快几倍

java - 使用 jpa 和 hibernate 在 spring 中延迟加载实体

java - Hibernate + Spring 的意外缓存

java - BeanException 在 Idea IDE 中没有正确解决

java - Spring 启动。尝试打印非存储实体时没有代理

java - Android: Volley HTTP 补丁请求

spring-boot - 已请求默认 Binder ,但没有可用于 'org.springframework.cloud.stream.messaging.DirectWithAttributesChannel' 的 Binder

tomcat - Websocket 服务器 Spring Boot