【问题标题】:How @Autowire gets the spring bean without using @Bean annotation@Autowire 如何在不使用 @Bean 注解的情况下获取 spring bean
【发布时间】:2019-10-07 10:32:43
【问题描述】:

我在 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接口是这样的:

package com.example.demo.jpa;

import java.util.List;

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

}

接口的实现:-

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();
    }

}

现在在我的控制器类中,我正在注入 AppRepo 对象

@Autowired
AppRepo appRepo;

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

【问题讨论】:

    标签: java spring spring-boot jpa


    【解决方案1】:

    如果你@Autowired AppRepoCustom,那将是模棱两可的。但在您的情况下,您有 @Autowired AppRepo ,它是 AppRepoCustom 接口的子级。所以 Spring 知道你已经要求提供子接口的 bean 并且没有错误地提供它。

    至于在AppRepo的情况下将自动装配哪个具体实现,请参阅spring文档中的以下参考。

    在这种情况下,我们指示 Spring 扫描 com.acme.repositories 及其所有子包以查找扩展 Repository 的接口或其子接口之一。对于找到的每个接口,它将注册特定于持久性技术的 FactoryBean 以创建相应的代理来处理查询方法的调用。

    更多详情read documentation

    【讨论】:

    • 是的,但是 AppRepo 没有任何 impl 类,所以它使用的是哪个实现类?
    • @GiteshkumarJha 我正在更新答案。
    • @GiteshkumarJha 如果这回答了您的问题,请您将其标记为正确。
    【解决方案2】:

    Spring boot 应用程序扫描所有带有标签的类,即@repository、@Component、@Bean、@Controller 等并创建对象。 此外,在你的情况下,你有 @Autowired 类 @Apprepo 所以没有冲突,它应该工作得很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-19
      • 2011-07-19
      • 2012-07-12
      • 1970-01-01
      • 2013-01-06
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多