Aydin
Aydin

Reputation: 331

Spring JPA is failing to autowire/inject bean beyond unit test, what have I done wrong?

I promise I have spent many hours reading documentation on spring.io, trying quick-start tutorials etc. but I just cannot figure out what I'm doing wrong. I have also looked through similar questions on here, and tried proposed solutions (where relevant). I'm sure it's something ridiculously simple, so I'm sorry for having to ask.

My repository:

@Repository
public interface SomethingRepository extends CrudRepository<Something, Integer> {

}

The configuration:

@Configuration
@EnableAutoConfiguration
@EntityScan("com.where.they.are") //changed for anonymity - assume correct
@EnableJpaRepositories("com.where.they.are") //changed for anonymity - assume correct
public class DatabaseConfigurationInTest {

}

Here is some class where I'm trying to inject my repository (it fails), it's always null:

public class SomethingDAO{
@Inject
private SomethingRepository somethingRepository;
}

But in this unit test, it works just fine, injection and everything.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = DatabaseConfigurationInTest.class)
@ActiveProfiles("local")
public class SomethingRepoTest{
    @Inject
    private SomethingRepository somethingRepository;

Upvotes: 0

Views: 183

Answers (1)

iamiddy
iamiddy

Reputation: 3073

To @Predrag Maric point , your class SomethingDAO could be annotated with @Service and make sure it`s package is reachable by componentScan

@Service
public class SomethingDAO{
@Inject
private SomethingRepository somethingRepository;
}

Upvotes: 1

Related Questions