Java 无法自动连线。没有';MessagingPropertiesRefactor';找不到类型
我见过其他与这个问题相关的问题,但没有一个真正有助于解决我的问题 我在测试类中定义了这两个属性Java 无法自动连线。没有';MessagingPropertiesRefactor';找不到类型,java,spring-boot,autowired,spring-bean,Java,Spring Boot,Autowired,Spring Bean,我见过其他与这个问题相关的问题,但没有一个真正有助于解决我的问题 我在测试类中定义了这两个属性 @Autowired private MessagingProperties messagingProperties; @Autowired private MessagingPropertiesRefactor messagingPropertiesRefactor; 我正在尝试创建MessagingProperties.java的新版本。我基本上复制了这个类,创建了一个新文
@Autowired
private MessagingProperties messagingProperties;
@Autowired
private MessagingPropertiesRefactor messagingPropertiesRefactor;
我正在尝试创建MessagingProperties.java的新版本。我基本上复制了这个类,创建了一个新文件MessagingPropertiesRefactor.java(相同的包/dir),并粘贴了相同的代码。我更改了类定义等,但大部分都是相同的
我收到IntelliJ设计时编译器错误,说明“无法自动连线。未找到'MessagingPropertiesRefactor'类型的bean。”
然后,我搜索了原始类的每一个用法,以再次检查它是否已在某处声明,但我没有找到任何东西
我是Java(和Spring)的“新手”。以前有人遇到过同样的问题吗?请确保
MessagingPropertiesRefactor
已将所有注释应用于MessagingProperties
具有的类。如果有,则在项目的xml配置中查找MessagingProperties
的bean定义,并制作一份副本。如果您的新类MessagingPropertiesRefactor未使用@Component
进行注释,则必须在beans.xml中声明它,如下所示:
<beans>
<bean name="messagingPropertiesRefactor" class="com.package.path.MessagingPropertiesRefactor"/>
</beans>
@Configuration
public class AppConfig {
@Bean
public MessagingPropertiesRefactor messagingPropertiesRefactor() {
return new MessagingPropertiesRefactor();
}
}
@RunWith(SpringRunner.class)
@ContextConfiguration
如果您想在测试中应用Spring依赖项注入,您有两个基本选项:
MessagingProperties
和MessagingPropertiesRefactor
,并按以下方式注释测试类:
@RunWith(SpringRunner.class)
@ContextConfiguration("your.xml")
bean应该成功地自动连线<beans>
<bean name="messagingPropertiesRefactor" class="com.package.path.MessagingPropertiesRefactor"/>
</beans>
@Configuration
public class AppConfig {
@Bean
public MessagingPropertiesRefactor messagingPropertiesRefactor() {
return new MessagingPropertiesRefactor();
}
}
@RunWith(SpringRunner.class)
@ContextConfiguration
2.2。在测试类中,定义上下文配置类,该类用于声明所需的bean:
@Configuration
static class Config {
@Bean
public MessagingProperties messagingProperties() {
// Assuming MessagingProperties has default ctor.
return new MessagingProperties();
}
// Same for MessagingPropertiesRefactor
}
享受自动连线bean:)*config类不必嵌套到测试类中
@Autowired
private MessagingProperties messagingProperties;
@Autowired
private MessagingPropertiesRefactor messagingPropertiesRefactor;
有关该主题的更多信息,请参阅Spring文档:,第3.5.4章。上下文管理。因此,我找到了一行“神奇”的代码,使它成为一个“bean”
显然,我需要做的就是将这个类添加到@EnableConfigurationProperties属性中。然后我可以通过@Autowired属性使用它
现在。。。为什么或者如何,我不知道(就像我说的,我是java的“新手”),我希望有人能详细解释一下。重构类是否有
@组件注释?如果不是,您应该在beans.xml文件或AppConfig类文件中声明此类的bean您的类MessagingPropertie
和MessagingPropertiesRefactor
是否注释为@ConfigurationProperties
?如果是这样的话,那就没有什么神奇的了:)正如注释@EnableConfigurationProperties
所说,您已经启用了它们,即将它们注册为bean。但是,这似乎不是autowire ConfigurationProperties的好方法。如果您正在寻找一种技术来自动连接bean,并像处理“普通”对象一样使用它们,即直接调用它们的方法,那么最好应用答案中提出的解决方案之一。虽然你的情况可能很具体,但问题并不十分清楚。