我无法使用@Repository注释类来使@Autowire注释工作。
我有一个接口:
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注释的类中,它总是为null。
我是不是遗漏了什么?
发布于 2013-11-13 22:10:12
您的问题很可能是您自己用new实例化这个bean,所以Spring没有意识到它。代之以注入bean,或者使bean @Configurable并使用AspectJ。
发布于 2013-11-08 10:16:37
您可能还没有将Spring注释配置为启用。我建议看看您的组件扫描注释。例如,在Java配置应用程序中:
@ComponentScan(basePackages = { "com.foo" })..。或XML配置:
<context:annotation-config />
<context:component-scan base-package="com.foo" />如果您的FooClass不在该配置中定义的基本包下,则将忽略@Autowired。
还有一点,我建议您尝试@Autowired(必需=真)--这应该会导致应用程序在启动时失败,而不是等到使用该服务抛出NullPointerException。但是,如果没有配置注释,那么就不会出现故障。
您应该使用JUnit测试来测试您的自动装配是否正确。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = MyConfig.class,
loader = AnnotationConfigContextLoader.class)
public class AccountRepositoryTest {
@Autowired
private AccountRepository accountRepository;
@Test
public void shouldWireRepository() {
assertNotNull(accountRepository);
}
}这应该表明您的基本配置是否正确。下一步,假设这是作为一个web应用程序部署的,将检查是否在web.xml和foo-servlet.xml配置中放置了正确的部分来触发Spring。
发布于 2013-11-08 10:05:13
FooClass需要由Spring实例化,以便管理他的依赖关系。确保将FooClass实例化为bean (@Component或@Service注释或XML声明)。
编辑:sessionFactory.setPackagesToScan正在寻找JPA/Hibernate注释,而@Repository是一个Spring注释。AccountRepositoryImpl应该在Spring component-scan范围内
致以敬意,
https://stackoverflow.com/questions/19856241
复制相似问题