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

时间:2019-10-07 10:32:43

标签: 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界面是​​这样的:

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中,那么此对象创建在这里如何工作?我很困惑。在给定场景下,当我们创建接口objectName = new implClass();之类的对象时,如何在内部创建对象。

2 个答案:

答案 0 :(得分:1)

如果您@Autowired AppRepoCustom,这将是模棱两可的。但是在您的情况下,您有@Autowired AppRepo AppRepoCustom 接口的子级。因此,Spring知道您已要求提供子接口bean并提供它,而不会出现错误。

关于在AppRepo情况下将自动装配的具体实现,请参见spring文档中的以下参考文献。

  

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

有关更多详细信息,read documentation

答案 1 :(得分:0)

Spring Boot应用程序扫描带有标签的所有类,例如@ repository,@ Component,@ Bean,@ Controller等并创建对象。 另外,在您的情况下,您已经@Autowired这个类@Apprepo,所以没有冲突,它应该可以正常工作。

相关问题