![](/img/trans.png)
[英]Consider defining a bean of type 'service' in your configuration [Spring boot]
[英]Consider defining a bean of type 'package' in your configuration [Spring-Boot]
我收到以下错误:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method setApplicant in webService.controller.RequestController required a bean of type 'com.service.applicant.Applicant' that could not be found.
Action:
Consider defining a bean of type 'com.service.applicant.Applicant' in your configuration.
我以前从未见过此错误,但奇怪的是 @Autowire 无法正常工作。 这是项目结构:
申请人界面
public interface Applicant {
TApplicant findBySSN(String ssn) throws ServletException;
void deleteByssn(String ssn) throws ServletException;
void createApplicant(TApplicant tApplicant) throws ServletException;
void updateApplicant(TApplicant tApplicant) throws ServletException;
List<TApplicant> getAllApplicants() throws ServletException;
}
申请人实施
@Service
@Transactional
public class ApplicantImpl implements Applicant {
private static Log log = LogFactory.getLog(ApplicantImpl.class);
private TApplicantRepository applicantRepo;
@Override
public List<TApplicant> getAllApplicants() throws ServletException {
List<TApplicant> applicantList = applicantRepo.findAll();
return applicantList;
}
}
现在我应该能够自动连接申请人并能够访问,但是在这种情况下,当我在我的@RestController:
@RestController
public class RequestController extends LoggingAware {
private Applicant applicant;
@Autowired
public void setApplicant(Applicant applicant){
this.applicant = applicant;
}
@RequestMapping(value="/", method = RequestMethod.GET)
public String helloWorld() {
try {
List<TApplicant> applicantList = applicant.getAllApplicants();
for (TApplicant tApplicant : applicantList){
System.out.println("Name: "+tApplicant.getIndivName()+" SSN "+tApplicant.getIndSsn());
}
return "home";
}
catch (ServletException e) {
e.printStackTrace();
}
return "error";
}
}
----------------------更新 1--------------------
我加了
@SpringBootApplication
@ComponentScan("module-service")
public class WebServiceApplication extends SpringBootServletInitializer {
@Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(WebServiceApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(WebServiceApplication.class, args);
}
}
错误消失了,但什么也没发生。 但是,当我在添加@ComponentScan()
之前在RestController
中注释掉与Applicant
打交道的所有内容时,我能够返回一个字符串UI
,这意味着我的RestController
正在工作,现在它被跳过了。 我现在丑陋Whitelabel Error Page
。
--------------------更新 2---------------------------- ---
我添加了它所抱怨的 bean 的基数 package。 错误内容如下:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method setApplicantRepo in com.service.applicant.ApplicantImpl required a bean of type 'com.delivery.service.request.repository.TApplicantRepository' that could not be found.
Action:
Consider defining a bean of type 'com.delivery.request.request.repository.TApplicantRepository' in your configuration.
我添加了@ComponentScan
@SpringBootApplication
@ComponentScan({"com.delivery.service","com.delivery.request"})
public class WebServiceApplication extends SpringBootServletInitializer {
@Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(WebServiceApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(WebServiceApplication.class, args);
}
}
--------------------------更新 3-------------------- --
添加:
@SpringBootApplication
@ComponentScan("com")
public class WebServiceApplication extends SpringBootServletInitializer {
仍然在抱怨我的ApplicantImpl
class,@ @Autowires
我的回购TApplicantRepository
到它。
这可能是因为该项目已分解为不同的模块。
@SpringBootApplication
@ComponentScan({"com.delivery.request"})
@EntityScan("com.delivery.domain")
@EnableJpaRepositories("com.delivery.repository")
public class WebServiceApplication extends SpringBootServletInitializer {
有机会...
您可能在各自的实现类上缺少@Service
、 @Repository
或@Component
注释。
您的申请人类似乎没有被扫描。 默认情况下,所有以根作为您放置@SpringBootApplication
的类的包都将被扫描。
假设您的main
类“WebServiceApplication”在“ com.service.something
”中,那么所有属于“ com.service.something
”的组件都会被扫描,而“ com.service.applicant
”将不会被扫描。
您可以重组您的包,使“WebServiceApplication”属于根包,而所有其他组件都成为该根包的一部分。 或者您可以包含@SpringBootApplication(scanBasePackages={"com.service.something","com.service.application"})
等,以便在 spring 容器中扫描和初始化“所有”组件。
根据评论更新
如果您有多个由 maven/gradle 管理的模块,则所有 spring 需要的是要扫描的包。 您告诉 spring 扫描“com.module1”并且您有另一个模块,其根包名称为“com.module2”,这些组件将不会被扫描。 你甚至可以告诉 spring 扫描“com” ,然后扫描“ com.module1.
”和“ com.module2.
”中的所有组件。
基本上,当您将类应用程序放在“另一个包”中时,就会发生这种情况。 例如:
com.server
- Applicacion.class (<--this class have @ComponentScan)
com.server.config
- MongoConfig.class
com.server.repository
- UserRepository
我在 Application.class 中解决了这个问题
@SpringBootApplication
@ComponentScan ({"com.server", "com.server.config"})
@EnableMongoRepositories ("com.server.repository") // this fix the problem
另一种不太优雅的方法是:将所有配置类放在同一个包中。
就我而言,我犯了一个可怕的错误。 我把@Service
放到了服务接口上。
为了解决这个问题,我将@Service
放在服务文件的实现上,它对我有用。
如果 bean 与 @Autowired 在同一个包中,那么它永远不会导致这样的问题。 但是,默认情况下,无法从不同的包访问 bean。 要解决此问题,请执行以下步骤:
@ComponentScan(basePackages = {"your.company.domain.package"})
public class SpringExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringExampleApplication.class, args);
}
}
如果您使用 Lombok 并且为字段添加了@RequiredArgsConstructor
和@NonNull
但您的某些字段不会注入到构造函数中,也会发生这种情况。 这只是获得相同错误的可能性之一。
参数 0 需要一个无法找到的 MissingBeanName 类型的 bean
在我的情况下,错误告诉我问题出在哪个控制器上,删除@NonNull
后应用程序开始正常
我在使用 Spring Boot 2 的 Maven 多模块项目中遇到了熟悉的问题。该问题与子 Maven 模块中的包命名有关。
@SpringBootApplication 封装了很多组件,例如 - @ComponentScan、@EnableAutoConfiguration、jpa-repositories、json-serialization 等等。 他将@ComponentScan 放在 com.*******.space 包中。 这部分包 com.*******.space 必须是所有模块通用的。
为了修复它:
对于通过谷歌搜索通用 bean 错误消息而被带到这里的任何人,但实际上是试图通过客户端界面上的@FeignClient
注释将 feign客户端添加到他们的 Spring Boot 应用程序,上述解决方案都不适合您。
要解决此问题,您需要将@EnableFeignClients
注释添加到您的 Application 类中,如下所示:
@SpringBootApplication
// ... (other pre-existing annotations) ...
@EnableFeignClients // <------- THE IMPORTANT ONE
public class Application {
旁注:在@SpringBootApplication
下添加@ComponentScan(...)
是多余的,您的 IDE 应该这样标记它(至少 IntelliJ IDEA 会这样做)。
我认为您可以通过使用@Repository
注释您的存储库来简化它,然后它将由 Spring Framework 自动启用。
就我而言,这两个选项有效。
在//@ComponentScan ({"myapp", "myapp.resources","myapp.services"})
中还包括在列表中包含Application.class
的包,或者
只需添加@EnableAutoConfiguration
; 它会自动识别所有的弹簧豆。
在应用程序中添加以下注释后,它对我有用:
@ComponentScan({"com.seic.deliveryautomation.mapper"})
我收到以下错误:
“构造函数的参数 1 需要一个找不到的映射器类型的 bean:
将 Springbootapplication(application.java) 文件移动到另一个包解决了我的问题。 将其与控制器和存储库分开。
我在网上寻求答案,但似乎没有一个适合我的情况的解决方案:一开始,一切正常,如下所示:
@Slf4j
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class GroupService {
private Repository repository;
private Service service;
}
然后我试图添加一个地图来缓存一些东西,它变成了这样:
@Slf4j
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class GroupService {
private Repository repository;
private Service service;
Map<String, String> testMap;
}
繁荣!
Description:
Parameter 4 of constructor in *.GroupService required a bean of type 'java.lang.String' that could not be found.
Action:
Consider defining a bean of type 'java.lang.String' in your configuration.
我删除了@AllArgsConstructor(onConstructor = @__(@Autowired))
并为除Map<String, String>
之外的每个repository
和service
添加@Autowired
。 它就像以前一样工作。
@Slf4j
@Service
public class SecurityGroupService {
@Autowired
private Repository repository;
@Autowired
private Service service;
Map<String, String> testMap;
}
希望这可能会有所帮助。
如果@Service 类被标记为抽象,就会发生这种情况。
就我而言,出现此错误是因为我的导入错误,例如,使用 spring,导入会自动出现:
import org.jvnet.hk2.annotations.Service;
但我需要:
import org.springframework.stereotype.Service;
@Configuration 注释只会解决错误
如果你不小心在两个不同的类中定义了同一个 bean,你也会得到这个错误。 那发生在我身上。 错误消息具有误导性。 当我删除额外的 bean 时,问题就解决了。
我的错误是我包括了:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
代替:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
我遇到了同样的问题。 Mongo DB 存储库由 Spring boot 识别,但它没有为扩展 mongo 存储库的存储库接口创建 Bean。
在我的情况下,问题是 maven pom 中“spring + mango”的版本规范不正确。 我已经更改了工件的组 ID,这一切都像魔术一样工作。 不需要注释,因为 spring boot 处理了所有事情。
在我的问题解决过程中,我在网上搜索解决方案并意识到这个问题实际上与项目配置有关,任何遇到此问题的人都应该首先检查他们的项目设置并从 spring 启用调试以获取更多关于失败的详细信息并密切关注正是在这个过程中,创建失败了。
尝试配置项目结构,如下所示:
将所有repo、service、packages放在主包的子包中:
package com.leisure.moviemax; //Parent package
@SpringBootApplication
@PropertySource(value={"classpath:conf.properties"})
public class MoviemaxApplication implements CommandLineRunner {
package com.leisure.moviemax.repo; //child package
@Repository
public interface UsrRepository extends JpaRepository<UserEntity,String> {
当您未能使用@Entity
Annotation 注释与您的 bean 关联的实体类时,也会弹出此错误消息。
我的ComponentScan
工作正常,但@repository
接口弹出了这个:
@Repository
public interface ExpenseReportAuditRepository extends
PagingAndSortingRepository<ExpenseReportAudit, Integer> {
因为我未能将 @Entity 注释添加到ExpenseReportAudit
@Entity // <--- Adding this fixed the issue.
public class ExpenseReportAudit {
.....
@SpringBootApplication
@MapperScan("com.developer.project.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
如果您的类依赖项由 Spring 管理,那么如果我们忘记在 POJO 类中添加默认/空 arg 构造函数,则可能会出现此问题。
它可能会帮助某人。 我有同样的问题,同样的错误信息,同样的一切。 我尝试了其他答案的解决方案,直到我意识到我正在使用的 bean 与实际自动装配的 bean 具有相同的名称时才有所帮助。 它发生在重构过程中,因此我不得不重命名该类,结果是积极的。 干杯
就我而言,我们的项目有一个配置类,所以我只是像这样添加了我的
@Configuration
public class DependencyConfiguration {
@Bean
public ActivityService activityService(
@Value("${send.money.ms.activity.url}") final String activityHistoryUrl,
final HttpRestService httpRestService
) {
return new ActivityServiceImpl(activityHistoryUrl, httpRestService);
}
.....................
然后微服务就正常启动了。
PS:即使我需要的库已正确导入并且可以在导入的外部库中看到,我也遇到了这个问题。
有同样的错误,表明这是应用程序属性的问题,用户名、密码和驱动程序不正确,与 Bean 完全无关。
我也收到了类似的错误:
Consider defining a bean of type 'A_REPOSITORY_INTERFACE' in your configuration.
然后,根据Akash e的解决方案,我将@EnableJpaRepositories
添加到我的主class。之后,我收到了以下错误:
Consider defining a bean of type 'entityManagerFactory' in your configuration.
接下来,我浏览了这里的所有回复,在谷歌上搜索了很多,并阅读了很多其他资源,但没有成功。
最后,我很幸运在博客/网站(javatute.com)上找到了解决方案。 我只是按照它的例子。
正如这里许多人所建议的那样,我将@ComponentScan("YOUR_BASE_PACKAGE.*")
和@EntityScan("YOUR_BASE_PACKAGE.*")
添加到我的主应用程序 class,然后添加config
package 并创建JpaConfig
class,例如:
package YOUR_BASE_PACKAGE.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories(basePackages = "YOUR_BASE_PACKAGE")
public class JpaConfig {
}
我关注的博客:
这导致我:
在 class 路径资源中创建名称为 entityManagerFactory 的 bean 时出错:调用 init 方法失败
最后到:
我有一个案例,我需要将 RestTemplate 注入服务类。 但是,服务类无法获取 RestTemplate。 我所做的是在与主应用程序相同的包下创建一个包装器类,并将包装器标记为 Component 并在服务类中自动装配该组件。 问题解决了。 希望它也适合你
我认为,您在 RequestController 中缺少 @Bean 注释
在您的文件中添加 Bean,这解决了我的问题
我在从 tutorialspoint 学习 Spring Boot 时得到了这个解决方案
private Applicant applicant;
@Bean
public Applicant applicant() {
return new Applicant();
}
添加 Spring Boot Data JPA Starter 依赖项为我解决了这个问题。
马文
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
摇篮
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.2.6.RELEASE'
或者你可以直接去这里
如果您使用interface
,您可以使用@Repository
注释扩展CrudRepository<Applicant,Long>
。
当您使用每个示例@EnableMongoRepositories(YOUR_MONGO_REPOSITORIES_PACKAGE)
并且稍后您重命名包名称或将其移动到另一个位置时,也会出现问题。
经常在多模块 Maven 项目和 Spring Boot 中遇到它
您有可能在实现接口之前尝试@autowired接口。
示例解决方案:
**HomeController.java**
class HomeController{
@Autowired
UserService userService;
.....
}
----------------------------------------------------------------------
**UserService.java**
public interface UserService {
User findByUsername(String username);
.....
}
-----------------------------------------------------------------------
**UserServiceImpl.java**
@Service
public class UserServiceImpl implements UserService{
public User findByUsername(String username) {
return userDao.findByUsername(username);
}
....
}
<i>This is not italic</i>, and [this is not a link](https://example.com)
从线程运行方法中移除注解类型配置,如@Service。
@Service, @Component
提醒一下 spring 不会扫描世界,它使用有针对性的扫描,这意味着存储 springbootapplication 的包下的所有内容。 因此,可能会出现此错误“考虑在配置 [Spring-Boot] 中定义 'package' 类型的 bean”,因为您在不同的 springbootapplication 包中有服务接口。
检查基本包名称。如果包有不同的模块,这些模块没有以基本包名称为前缀。
要修复以下错误:
我碰巧LocalContainerEntityManagerFactoryBean
类没有setPackagesToScan
方法。 然后我继续使用无法正常工作的@EntityScan
注释。
后来我可以找到方法setPackagesToScan()
但在另一个模块中,所以问题来自没有此方法的依赖项,因为它是旧版本。
此方法可以在更新版本的spring-data-jpa或spring-orm依赖项中找到:
从:
implementation("org.springframework", "spring-orm", "2.5.1")
至:
implementation("org.springframework", "spring-orm", "5.2.9.RELEASE")
或者:
implementation("org.springframework.data", "spring-data-jpa", "2.3.4.RELEASE")
此外,除了@SprintBootApplication
之外,不需要添加其他注释。
@SpringBootApplication
open class MoebiusApplication : SpringBootServletInitializer()
@Bean
open fun entityManagerFactory() : LocalContainerEntityManagerFactoryBean {
val em = LocalContainerEntityManagerFactoryBean()
em.dataSource = dataSource()
em.setPackagesToScan("app.mobius.domain.entity")
...
}
总帐
对我来说,在 pom.xml 上进行了全新安装
右键单击 pom.xml
展开运行方式
选择 Maven 构建
将目标设置为命令clean install
应用 > 运行 > 关闭
如果您正在使用 Eclipse 并尝试了所有可能性,但仍然有错误,请尝试使用 Maven 更新项目。 您可以这样: Right click on your project-> Maven -> Update Project
。
它帮助我解决了我的错误。 如果项目未使用您在 pom 文件中声明的所有 repos 更新,有时 Eclipse 会显示此错误。
由于@Repository 类的basePackages 名称不正确,我在使用MongoDB 时遇到了同样的问题
@Configuration
@EnableMongoRepositories(basePackages = {"org.mycompany.repository.mongo.primary"}, mongoTemplateRef = "getMongoTemplatePrimary")
我有一个类似的问题,完全相同的错误消息。 但是我的错误只发生在我尝试在本地 docker 上安装和运行时。
原来这个问题取决于个人资料。
我有两个实现接口的类,一个带有生产配置文件@Profile("prod"),第二个带有“测试环境”配置文件。 @Profile("!local & !prod")
但是,当我尝试在本地(在 Docker 上)运行时没有活动配置文件。
我创建了一个为本地配置文件 @Profile("local") 实现接口的第三类,这解决了我的问题
就我而言,我刚刚为某些类添加了@Component
注释(以确保每个类都有配置)。
@Component
、 @Service
或@Repository
几乎很熟悉。 Baeldung链接参考
就我而言,这个问题是由错误的spring.autoconfigure.exclude
属性值引起的。 我有这个属性是因为我的 Spring Boot 项目最初没有连接到数据库,但后来我添加了我的第一个JpaRepository
类并尝试在@RestController
类中使用@Autowired
注释声明它的一个实例。
application.properties
中导致问题的行:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
一旦我删除或注释掉该行,我的 Spring Boot 服务就运行得很好。
对我来说,这是因为在使用lombok @RequiredArgsConstructor注释的类中使用了@Value。 只是将其更改为构造函数注入。
我遇到了同样的问题,我在 redis 存储库中遇到了这个错误,如下所示:
@Repository
public interface AppTokenRepository extends CrudRepository<AppToken, String> {
}
@RedisHash("APP_TOKEN")
public class AppToken implements Serializable {
private String id;
private String accessToken;
}
我通过在 Spring Boot 应用程序类上添加@EnableRedisRepositories
解决了我的问题。
@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
@EnableHystrix
@EnableHystrixDashboard
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
如果您有两个同名的bean ,也会发生这种情况。
例如,如果您有工厂方法monkey
创建 Monkey 并且您错误地将另一个工厂方法(创建 Car)命名为monkey
。
有问题的代码:
@Bean
public Car monkey() {
return new Car();
}
应该:
@Bean
public Car car() {
return new Car();
}
参考:
默认情况下,bean 名称将与方法名称相同...
按属性名称自动装配。 Spring 查找与需要自动装配的属性同名的 bean。 例如,如果一个 bean 定义被设置为按名称自动装配并且它包含一个 master 属性(也就是说,它有一个 setMaster(..) 方法),Spring 查找一个名为 master 的 bean 定义并使用它来设置该属性。
对于没有找到 Bean 的 Class 使用@Component
。 并使用
@ComponentScan("<Use_The_Root_Directory_Of_Main_Class>")
. 当组件分布在许多目录中时,可能会发生这种情况。
@Configuration
@SpringBootApplication
@ComponentScan({"com.example.demo"})
public class Application {
}
对我来说 - 使用 Spring Boot 和 MongoDB,以下是问题:
在我的 POM.xml 中,我有:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-starter-data-mongodb</artifactId>
</dependency>
但我需要以下内容:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
(简短:添加“spring-boot-...”而不是仅“spring-...”)
@Service
应该从org.springframework.stereotype.Service
导入
您可能从org.jvnet.hk2.annotations.Service
导入它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.