gpt4 book ai didi

java - 我可以从另一个使用 @Autowired 的项目调用方法吗?

转载 作者:行者123 更新时间:2023-12-02 11:41:17 24 4
gpt4 key购买 nike

我试图从我使用依赖项导入的第二个项目中调用方法。

此方法包装在一个类中,我使用 @Bean 注释在项目中实例化该类。问题出在这个类中,我有一个 @Autowired 来获取第二个项目的另一个类,当我尝试运行它时,它无法解决此连接。

有什么方法可以调用它吗?

更新

这是一个例子:

在我的项目 A 中,我有下一个类:

@Component
public class Logger {

private static final Logger logger =
LoggerFactory.getLogger(Logger.class);

@Autowired
private RabbitTemplate template;

@Autowired
private DirectExchange exchange;
}

从项目 B 我得到带有 Maven 依赖项的项目 A。

在项目 B 中我有:

public class OperatorSdkAmqpPollTests {

private static final Logger logger =
LoggerFactory.getLogger(OperatorSdkAmqpPollTests.class);

@Autowired
private Logger logger;
}

当我运行它时,出现以下错误:

Field exchange in com.minsait.cybersec.netvote.common.core.Logger required a bean of type 'org.springframework.amqp.core.DirectExchange' 

还要添加我在 Spring Boot 下运行它,以便自动定义 RabbitTemplate,当我在项目 A 中运行测试时,它运行时不会出现问题,DirectExchange 在项目 A 中的类中定义,如下所示:

@SpringBootApplication
public class AmqpConfig {

@Bean
public Queue worksQueue() {
return new Queue("queue");
}

@Bean
public DirectExchange exchange() {
return new DirectExchange("exchange");
}
}

最佳答案

在您的项目 B 中,您的类 Logger 不被称为 bean,因为注释 @Component 在项目范围内定义了您的类 Logger A. 解决方案非常简单:在项目 B 中的 Spring 的 XML 配置文件中添加您的 Logger 类的 bean 定义。然后它将在您的项目 B 中称为 Bean,一切都会正常。
因此,在 MyOwnappricationContext.xml 中的某处执行以下操作:

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

...

<bean id="logger" name="logger" class="com.minsait.cybersec.my.package.from.project.a.Logger"/>
</beans>

关于java - 我可以从另一个使用 @Autowired 的项目调用方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48522247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com