本文介绍了@Autowire因@Repository失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使@Autowire注释与@Repository注释类一起工作.

I am not being able to make @Autowire annotation work with a @Repository annotated class.

我有一个界面:

public interface AccountRepository {
    public Account findByUsername(String username);
    public Account findById(long id);
    public Account save(Account account);
}

以及实现接口的类带有@Repository 注释的:

And the class implementing the interface annotated with @Repository:

@Repository
public class AccountRepositoryImpl implements AccountRepository {
    public Account findByUsername(String username){
        //Implementing code
    }
    public Account findById(long id){
        //Implementing code
    }
    public Account save(Account account){
        //Implementing code
    }
}

在另一个类中,我需要使用此存储库通过用户名查找帐户,因此我正在使用自动装配,但是我正在检查它是否有效并且accountRepository实例始终为空:

In another class, I need to use this repository to find an account by the username, so I am using autowiring, but I am checking if it works and the accountRepository instance is always null:

@Component
public class FooClass {
    @Autowired
    private AccountRepository accountRepository;

    ...

    public barMethod(){
        logger.debug(accountRepository == null ? "accountRepository is NULL" : "accountRepository IS NOT NULL");
    }
}

我还设置了程序包以扫描组件(sessionFactory.setPackagesToScan(new String [] {"com.foo.bar"});),它会自动装配其他以@Component注释的类,但是在此以@Repository注释的类中,它始终为空.

I have also set the packages to scan for the components (sessionFactory.setPackagesToScan(new String [] {"com.foo.bar"});), and it does autowire other classes annotated with @Component for instance, but in this one annotated with @Repository, it is always null.

我想念什么吗?

推荐答案

您的问题很可能是您自己使用new实例化了bean,因此Spring并不知道它.而是注入Bean,或者将Bean制成@Configurable并使用AspectJ.

Your problem is most likely that you're instantiating the bean yourself with new, so that Spring isn't aware of it. Inject the bean instead, or make the bean @Configurable and use AspectJ.

这篇关于@Autowire因@Repository失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 03:15