【发布时间】:2018-07-30 08:48:21
【问题描述】:
我正在使用 Spring Boot,但在理解 Beans 时遇到了一些麻烦。我被引导相信 Beans 替换了 new 关键字。
我发现仅使用 Autowire 时,我的 Beans 不会在对象上创建新实例,并且我的 REST 应用程序将返回用户首先要求的相同响应(即,如果我最初访问 url/id/1,然后访问 url/id/2 REST 响应将与 url/id/1 相同)。
我试图通过创建一个@Configuration 文件来定义一个 bean 来解决这个问题。
@Configuration
public class UserConfig {
@Autowired
UserDAO DAO;
@Bean
public User getUser(int uid) {
try {
return DAO.getUser(uid);
} catch (SIDException e) {
return null;
}
}
}
但我在运行时不断收到此错误:Parameter 0 of method getUser in com.application.Config.UserConfig required a bean of type 'int' that could not be found.
我不明白这一点,因为我试图在配置文件中定义 Bean。
在我的主文件中,我有这些注释:
@SpringBootApplication(scanBasePackages = {"com.application.Config","com.application"})
@ComponentScan({"com.application.Config","com.application"})
如果有帮助,我会在这种情况下使用我的 bean:
@Service
public class UserService {
@Autowired
private UserDAO DAO;
public User getUser(int uid) {
try {
return DAO.getUser(uid);
} catch (SIDException e) {
return null;
}
}
}
谢谢你:)
【问题讨论】:
-
问题是因为你有一个
@Bean注释,spring 会尝试选择它,期望int参数也是Bean- 你没有语境。看起来只需用@Service替换@Bean就可以了。如果可行,我可以将其作为答案-但我手头没有环境来测试...
标签: java spring spring-boot