@Autowire 因 @Repository 而失败 [英] @Autowire failing with @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 注释:
@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 而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!