gpt4 book ai didi

spring - 预计至少有 1 个有资格作为此依赖项的 Autowiring 候选者的 bean

转载 作者:行者123 更新时间:2023-12-02 04:09:47 25 4
gpt4 key购买 nike

我对 Spring 非常陌生,正在尝试在 Spring Boot 中开发一个应用程序。我知道这是重复的问题,但我没有找到任何解决我的问题的方法。我有一个名为 UserController 的类,如下所示

    @RestController
public class UserController {

private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
private final UserService userService;

DatabaseConnections dataconnections = new DatabaseConnections();
@Autowired
private DAO dao;
@Inject
public UserController(final UserService userService) {
this.userService = userService;
}

@RequestMapping(value = "/user", method = RequestMethod.POST)
public User createUser(@RequestBody @Valid final User user) {
LOGGER.debug("Received request to create the {}", user);
return userService.save(user);
}
@RequestMapping(value = "/getuser/{id}", method = RequestMethod.GET)
public JSONObject getUser(@PathVariable String id) {

return dao.getUsers(id);
}
}

我还有一个具有某些功能的类:

@Service("dao")
public class DAO {
public JSONObject getUsers(@PathVariable String id) {
Connection dbConnection = null;
Statement statement = null;
JSONObject userJSONObject = new JSONObject();
String selectusers = "SELECT* from emp;
try {
dbConnection = dataconnections.getPostgresConnection(hostname, port, dbname, username, password);
statement = dbConnection.createStatement();
ResultSet rs = statement.executeQuery(selectusers);
while (rs.next()) {
--
---
}
return userJSONObject;
}

我想在usercontroler类中使用getUsers函数

当我尝试通过这种方式执行操作时,出现以下错误。

    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies  
failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire
field: private com.emc.bdma.itaudemo.postgres.dao.DAO
com.emc.bdma.itaudemo.restclient.controller.UserController.dao; nested
exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.emc.bdma.itaudemo.postgres.dao.DAO] found for
dependency: expected at least 1 bean which qualifies as autowire candidate for
this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}

最佳答案

似乎还没有找到你的 DAO 对象。我建议使用 @Service 注释来注释 DAO,如下所示:

@Service("dao")
public class DAO {
}

然后将其注入(inject)到您使用 @Autowired 注释的类中:

@Autowire
private DAO dao;

此外,您还可以以类似的方式 Autowiring 接口(interface),然后指定如果有多个接口(interface),将使用哪个实现。

如果不是这种情况,请发布调用 dao 函数的类的完整代码,以便我们可以看到全貌。

关于spring - 预计至少有 1 个有资格作为此依赖项的 Autowiring 候选者的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31185679/

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