我已经创建了一个简单的单元测试,但是IntelliJ错误地将它突出显示为红色。将其标记为错误

没有豆子?

如你所见,它通过了测试?所以它一定是自动连接的?


当前回答

在存储库类上添加Spring注释@Repository。

我知道没有这个注释它也能工作。但是如果添加了这个,IntelliJ将不会显示错误。

@Repository
public interface YourRepository ...
...

如果您将Spring Data与扩展Repository类一起使用,则会产生冲突包。那么你必须直接标明包裹。

import org.springframework.data.repository.Repository;
...

@org.springframework.stereotype.Repository
public interface YourRepository extends Repository<YourClass, Long> {
    ...
}

接下来,您可以自动连接存储库而不会出现错误。

@Autowired
YourRepository yourRepository;

这可能不是一个好的解决方案(我猜您试图注册存储库两次)。但是为我工作,不要出错。

也许在IntelliJ的新版本中可以修复:https://youtrack.jetbrains.com/issue/IDEA-137023

其他回答

你所需要做的是让这个工作是以下代码:

@ComponentScan
public class PriceWatchTest{

    @Autowired
    private PriceWatchJpaRepository priceWatchJpaRepository;
...
...
}

有时需要指明@ComponentScan应该在哪里扫描组件。你可以通过将包作为这个注释的参数来实现,例如:

@ComponentScan(basePackages={"path.to.my.components","path.to.my.othercomponents"})

然而,正如前面提到的,@SpringBootApplication注释替换了@ComponentScan,因此在这种情况下,你必须做同样的事情:

@SpringBootApplication(scanBasePackages={"path.to.my.components","path.to.my.othercomponents"})

至少在我的案例中,Intellij停止了抱怨。

在最新的IntelliJ中,这似乎仍然是一个bug,与可能的缓存问题有关?

如果您将@Repository注释添加为上面提到的mk321,保存,然后删除注释并再次保存,这将解决问题。

在bean配置文件中放置@Component或@configuration似乎可以工作,例如:

@Configuration
public class MyApplicationContext {
    @Bean
    public DirectoryScanner scanner() {
        return new WatchServiceDirectoryScanner("/tmp/myDir");
    }
}

@Component
public class MyApplicationContext {
    @Bean
    public DirectoryScanner scanner() {
        return new WatchServiceDirectoryScanner("/tmp/myDir");
    }
}

在类级别使用@EnableAutoConfiguration注释和@Component。它将解决这个问题。

例如:

@Component
@EnableAutoConfiguration  
public class ItemDataInitializer  {

    @Autowired
    private ItemReactiveRepository itemReactiveRepository;

    @Autowired
    private MongoOperations mongoOperations;
}