@Autowire failing with @Repository

南楼画角 提交于 2019-12-01 20:56:50

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.

It seems likely that you haven't configured your Spring annotations to be enabled. I would recommend taking a look at your component scanning annotations. For instance in a Java config application:

@ComponentScan(basePackages = { "com.foo" })

... or XML config:

<context:annotation-config />
<context:component-scan base-package="com.foo" />

If your FooClass is not under the base-packages defined in that configuration, then the @Autowired will be ignored.

As an additional point, I would recommend trying @Autowired(required = true) - that should cause your application to fail on start-up rather than waiting until you use the service to throw a NullPointerException. However, if annotations are not configured, then there will be no failure.

You should test that your autowiring is being done correctly, using a JUnit test.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
    classes = MyConfig.class, 
    loader = AnnotationConfigContextLoader.class)
public class AccountRepositoryTest {

    @Autowired
    private AccountRepository accountRepository;

    @Test
    public void shouldWireRepository() {
        assertNotNull(accountRepository);
    }

}

This should indicate whether your basic configuration is correct. The next step, assuming that this is being deployed as a web application, would be to check that you have put the correct bits and pieces in your web.xml and foo-servlet.xml configurations to trigger Spring initialisation.

FooClass needs to be instancied by Spring to have his depencies managed. Make sure FooClass is instancied as a bean (@Component or @Service annotation, or XML declaration).

Edit : sessionFactory.setPackagesToScan is looking for JPA/Hibernate annotations whereas @Repository is a Spring Context annotation. AccountRepositoryImpl should be in the Spring component-scan scope

Regards,

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!