【发布时间】:2013-11-08 10:02:00
【问题描述】:
我无法使@Autowire 注释与@Repository 注释类一起工作。
我有一个界面:
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 实例始终为空:
@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 注释的类中,它始终为空。
我错过了什么吗?
【问题讨论】:
-
您如何获得对
FooClass的引用?你是说FooClass foo = new FooClass();? -
你发现了问题,我得到了一个
new的引用而不是自动装配。如果您想接受它作为正确的回复,请发布回复。真的谢谢!
标签: spring annotations repository autowired