gpt4 book ai didi

java - Spring、Bean、构造函数参数作为字符串

转载 作者:行者123 更新时间:2023-12-01 19:33:29 25 4
gpt4 key购买 nike

我遇到了一个异常:没有找到依赖项 [java.lang.String] 的合格 bean:预计至少有 1 个符合 Autowiring 候选资格的 bean。

在 beans.xml 中

<bean id = "database" class = "com.price.compare.service.DAO" scope="singleton">
<constructor-arg index="0" type = "java.lang.String" value="localhost"/>
<constructor-arg index="1" type = "java.lang.String" value="5432"/>
</bean>

DAO.java

    @Component    public class DAO {        private final String host;        private final String port;        public DAO(String host, String port) {            this.host = host;            this.port = port;        }        @PostConstruct        public void init() {            // custom initialization logic        }    }

最佳答案

您已定义该 bean 两次;在 XML 配置中作为 @Component bean 。

通过使用@Component注释,在组件扫描期间拾取bean。但由于组件扫描时所需的字符串参数不明确,因此抛出异常。

从您的 bean 中删除 @Component 注释,让您的 XML 配置 bean 成为唯一的 DAO bean。

关于java - Spring、Bean、构造函数参数作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58661230/

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