Spring @ComponentScan没有被选中,可能是因为@SpringBootApplication中的@EnableAutoConfiguration ?

时间:2022-04-08 17:18:28

i'm new to SpringBoot and am currently reaching to understand the base functionality for a spring application with hibernate.

我是SpringBoot的新手,目前正在了解使用hibernate的spring应用程序的基本功能。

I have a package com.yyyyyyyyyyy.coaching and if I put all @Entity definitions there the app runs successfully. I was happy to get up and running quick.

我有一个包裹。如果我把所有的@Entity定义放在那里,应用程序就会成功运行。我很高兴起来,跑得很快。

Now I moved one entity to com.yyyyyyyyyyy.i18n.bo since it should later be used elsewhere and hibernate throws the following error:

现在我移动了一个实体到com。yyyyyyyyyyyyyyyyyyyyyyyyy .i18n。bo因为以后应该在其他地方使用它,hibernate会抛出以下错误:

Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.yyyyyyyyyyy.coaching.bo.Topic.descriptionStrings references an unknown entity: com.yyyyyyyyyyy.i18n.bo.Localized

(see below for the full --debug application startup)

(参见下面的完整——调试应用程序启动)

I understand that @ComponentScan should be used to specify which packages are scanned for annotations.

我理解应该使用@ComponentScan来指定要为注释扫描哪些包。

I have double checked that javax.persistence.Entity is used everywhere and not the one from the hibernate package.

我已经检查过javax.persistence。实体在任何地方都使用,而不是从hibernate包中使用的。

Here is my program entry point:

这是我的项目入口点:

@SpringBootApplication(scanBasePackages={"com.yyyyyyyyyyy"})
//@Configuration
//@ComponentScan(basePackages={"com.yyyyyyyyyyy.coaching", "com.yyyyyyyyyyy.i18n"})
@Import(AppConfig.class)
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

It doesn't find the Entity with scanBasePackages, with ComponentScan on the main class and also when using @Import and another config class "AppConfig". I also tried to use the ApplicationBuilder instead of SpringApplication like this new SpringApplicationBuilder().sources(AppConfig.class).main(DemoApplication.class).run(args); but to no avail.

它没有找到使用scanBasePackages、在主类上使用ComponentScan的实体,也没有找到使用@Import和另一个配置类“AppConfig”的实体。我还尝试使用ApplicationBuilder而不是SpringApplication,比如这个新的SpringApplicationBuilder().sources(AppConfig.class).main(DemoApplication.class).run(args);但无济于事。

What I can see from the debug output is the line:

我从调试输出中看到的是一行:

2015-11-18 08:08:48.407 DEBUG 13780 --- [           main] o.s.b.a.AutoConfigurationPackages        : @EnableAutoConfiguration was declared on a class in the package 'com.yyyyyyyyyyy.coaching'. Automatic @Repository and @Entity scanning is enabled.

I suppose this doesn't hurt as it comes from the @SpringBootApplication annotation

我想这不会有什么坏处,因为它来自@SpringBootApplication注释

The AppConfig class doesn't seem to be included either, as I added debug output which isn't printed.

AppConfig类似乎也不包含在内,因为我添加了未打印的调试输出。

@Configuration
//@Profile("production")
@ComponentScan(basePackages={"com.yyyyyyyyyyy.coaching", "com.yyyyyyyyyyy.i18n"})
public class AppConfig {
    public AppConfig() {
        System.out.println("------------------------------Init AppConfig-------------------------");
    }
    @PostConstruct
    public void doSomething() {
        System.out.println("------------------------------Done AppConfig-------------------------");
    }
}

Any help/ideas on this? Thanks.

任何帮助/想法吗?谢谢。

Edit, prj structure: Spring @ComponentScan没有被选中,可能是因为@SpringBootApplication中的@EnableAutoConfiguration ?

编辑,撮合下结构:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.0.RELEASE)

2015-11-18 08:08:47.048  INFO 13780 --- [           main] c.yyyyyyyyyyy.coaching.DemoApplication   : Starting DemoApplication on Suse with PID 13780 (started by Klaus in C:\Users\Klaus\Downloads\demo (1)\demo)
2015-11-18 08:08:47.051  INFO 13780 --- [           main] c.yyyyyyyyyyy.coaching.DemoApplication   : No profiles are active
2015-11-18 08:08:47.051 DEBUG 13780 --- [           main] o.s.boot.SpringApplication               : Loading source class com.yyyyyyyyyyy.coaching.DemoApplication
2015-11-18 08:08:47.098 DEBUG 13780 --- [           main] o.s.b.c.c.ConfigFileApplicationListener  : Loaded config file 'classpath:/application.properties'
2015-11-18 08:08:47.098 DEBUG 13780 --- [           main] o.s.b.c.c.ConfigFileApplicationListener  : Skipped (empty) config file 'classpath:/application.properties' for profile default
2015-11-18 08:08:47.103  INFO 13780 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1fc32e4f: startup date [Wed Nov 18 08:08:47 CET 2015]; root of context hierarchy
2015-11-18 08:08:47.106 DEBUG 13780 --- [           main] ationConfigEmbeddedWebApplicationContext : Bean factory for org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1fc32e4f: org.springframework.beans.factory.support.DefaultListableBeanFactory@7a1a3478: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,demoApplication]; root of factory hierarchy
2015-11-18 08:08:48.286  INFO 13780 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2015-11-18 08:08:48.407 DEBUG 13780 --- [           main] o.s.b.a.AutoConfigurationPackages        : @EnableAutoConfiguration was declared on a class in the package 'com.yyyyyyyyyyy.coaching'. Automatic @Repository and @Entity scanning is enabled.
2015-11-18 08:08:48.995  INFO 13780 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$4e01ef7c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2015-11-18 08:08:49.038 DEBUG 13780 --- [           main] ationConfigEmbeddedWebApplicationContext : Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@2e17a321]
2015-11-18 08:08:49.038 DEBUG 13780 --- [           main] ationConfigEmbeddedWebApplicationContext : Using ApplicationEventMulticaster [org.springframework.context.event.SimpleApplicationEventMulticaster@521bb1a4]
2015-11-18 08:08:49.368 DEBUG 13780 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Code archive: C:\Users\Klaus\.m2\repository\org\springframework\boot\spring-boot\1.3.0.RELEASE\spring-boot-1.3.0.RELEASE.jar
2015-11-18 08:08:49.369 DEBUG 13780 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Code archive: C:\Users\Klaus\.m2\repository\org\springframework\boot\spring-boot\1.3.0.RELEASE\spring-boot-1.3.0.RELEASE.jar
2015-11-18 08:08:49.369 DEBUG 13780 --- [           main] .t.TomcatEmbeddedServletContainerFactory : None of the document roots [src/main/webapp, public, static] point to a directory and will be ignored.
2015-11-18 08:08:49.419  INFO 13780 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2015-11-18 08:08:49.433  INFO 13780 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2015-11-18 08:08:49.434  INFO 13780 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.28
2015-11-18 08:08:49.566  INFO 13780 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2015-11-18 08:08:49.566  INFO 13780 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2467 ms
[..]
2015-11-18 08:08:49.960  INFO 13780 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2015-11-18 08:08:49.960  INFO 13780 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2015-11-18 08:08:49.961  INFO 13780 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2015-11-18 08:08:49.961  INFO 13780 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2015-11-18 08:08:49.982 DEBUG 13780 --- [ost-startStop-1] o.s.b.c.web.OrderedRequestContextFilter  : Initializing filter 'requestContextFilter'
2015-11-18 08:08:49.984 DEBUG 13780 --- [ost-startStop-1] o.s.b.c.web.OrderedRequestContextFilter  : Filter 'requestContextFilter' configured successfully
2015-11-18 08:08:49.985 DEBUG 13780 --- [ost-startStop-1] .s.b.c.w.OrderedHttpPutFormContentFilter : Initializing filter 'httpPutFormContentFilter'
2015-11-18 08:08:49.985 DEBUG 13780 --- [ost-startStop-1] .s.b.c.w.OrderedHttpPutFormContentFilter : Filter 'httpPutFormContentFilter' configured successfully
2015-11-18 08:08:49.985 DEBUG 13780 --- [ost-startStop-1] o.s.b.c.w.OrderedHiddenHttpMethodFilter  : Initializing filter 'hiddenHttpMethodFilter'
2015-11-18 08:08:49.985 DEBUG 13780 --- [ost-startStop-1] o.s.b.c.w.OrderedHiddenHttpMethodFilter  : Filter 'hiddenHttpMethodFilter' configured successfully
2015-11-18 08:08:49.985 DEBUG 13780 --- [ost-startStop-1] o.s.b.c.w.OrderedCharacterEncodingFilter : Initializing filter 'characterEncodingFilter'
2015-11-18 08:08:49.985 DEBUG 13780 --- [ost-startStop-1] o.s.b.c.w.OrderedCharacterEncodingFilter : Filter 'characterEncodingFilter' configured successfully
2015-11-18 08:08:50.825  INFO 13780 --- [           main] liquibase                                : Successfully acquired change log lock
2015-11-18 08:08:50.917  INFO 13780 --- [           main] liquibase                                : Reading from broadleaf.DATABASECHANGELOG
2015-11-18 08:08:50.926  INFO 13780 --- [           main] liquibase                                : Successfully released change log lock
2015-11-18 08:08:51.116  INFO 13780 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2015-11-18 08:08:51.128  INFO 13780 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2015-11-18 08:08:51.210  INFO 13780 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {4.3.11.Final}
2015-11-18 08:08:51.211  INFO 13780 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2015-11-18 08:08:51.214  INFO 13780 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2015-11-18 08:08:51.394  INFO 13780 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2015-11-18 08:08:51.441  INFO 13780 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2015-11-18 08:08:51.557  WARN 13780 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
2015-11-18 08:08:51.567  INFO 13780 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2015-11-18 08:08:51.574  INFO 13780 --- [           main] .b.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [ ...
2015-11-18 08:08:51.578 ERROR 13780 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1051) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:828) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) ~[spring-context-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.doRun(SpringApplication.java:347) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:295) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1112) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1101) [spring-boot-1.3.0.RELEASE.jar:1.3.0.RELEASE]
    at com.yyyyyyyyyyy.coaching.DemoApplication.main(DemoApplication.java:23) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1249) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.access$600(EntityManagerFactoryBuilderImpl.java:120) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:860) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343) ~[spring-orm-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318) ~[spring-orm-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
... 16 common frames omitted
Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.yyyyyyyyyyy.coaching.bo.Topic.descriptionStrings references an unknown entity: com.yyyyyyyyyyy.i18n.bo.Localized

1 个解决方案

#1


1  

Move DemoApplication class to com.yyyyyyyyyyy package and everything should work. Everything which is in com.yyyyyyyyyyy should be picked automatically.

将DemoApplication类移动到com。yyyyyyyyyyyyyyyyy包和一切都应该工作。一切在com。yyyyyyyyyyyyy应该是自动选择的。

Check this out how spring boot recommend structuring

检查一下spring boot如何推荐结构

UPDATE:

更新:

also as you saw in the ref documentation add add @EntityScan(basePackages={"com.yyyyyyyyyyy.coaching", "com.yyyyyyyyyyy.i18n"})to DemoApplication will work.

同样,正如您在ref文档中看到的,添加@EntityScan(basePackages={“com. yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy”)。指导学生降职是有效的。

#1


1  

Move DemoApplication class to com.yyyyyyyyyyy package and everything should work. Everything which is in com.yyyyyyyyyyy should be picked automatically.

将DemoApplication类移动到com。yyyyyyyyyyyyyyyyy包和一切都应该工作。一切在com。yyyyyyyyyyyyy应该是自动选择的。

Check this out how spring boot recommend structuring

检查一下spring boot如何推荐结构

UPDATE:

更新:

also as you saw in the ref documentation add add @EntityScan(basePackages={"com.yyyyyyyyyyy.coaching", "com.yyyyyyyyyyy.i18n"})to DemoApplication will work.

同样,正如您在ref文档中看到的,添加@EntityScan(basePackages={“com. yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy”)。指导学生降职是有效的。