Spring Boot 使用 Spring Profile 忽略来自 Java 配置类的 bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23959995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:25:33  来源:igfitidea点击:

Spring Boot ignores beans from Java config class using Spring Profile

javaspringmavenspring-bootspring-profiles

提问by Didasko

When I run my application on Eclipse with a classical context loading, no worries, the beans defines on the config class corresponding with the Spring Profile chosen are correctly instanciated.

当我使用经典上下文加载在 Eclipse 上运行我的应用程序时,不用担心,与所选 Spring Profile 对应的配置类上定义的 bean 被正确实例化。

public class BasketHandlerLoader {

    public static void main(String[] args) throws Exception {
        @SuppressWarnings("resource")
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:config/spring/spring-archibald-basket-handler-context.xml");
        context.registerShutdownHook();
    }
}

But, when I run the application with Spring Boot, these beans are not instanciated.

但是,当我使用 Spring Boot 运行应用程序时,这些 bean 没有被实例化。

@Configuration
@ImportResource("classpath:config/spring/spring-archibald-basket-handler-context.xml")
public class BasketHandlerLoader {

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

Here is the java configuration class for the "dev" Spring profile:

这是“dev” Spring 配置文件的 java 配置类:

@Configuration
@Profile("dev")
@EnableTransactionManagement
@PropertySources(value = { @PropertySource("classpath:filters/dev.properties") })
public class DevPersistenceConfig extends AbstractPersistenceConfig {

    @Inject
    private Environment env;

    @Override
    @Bean
    public DataSource dataSource() {
        return super.createDataSource(env);
    }

    @Override
    public Properties hibernateProperties() {
        return super.createHibernateProperties(env);
    }
}

Here the AbstractPersistenceConfigclass containing the others beans not instanciated:

这里AbstractPersistenceConfig类包含未实例化的其他 bean:

public abstract class AbstractPersistenceConfig {

    // Constants...

    // ************************** ABSTRACT METHODS **************************

    /**
    * Returns a property list containing the Hibernate properties.
    * 
    * @return the Hibernate properties.
    */
    public abstract Properties hibernateProperties();

    /**
    * Defines the application datasource bean corresponding with the current Spring Profile.
    * 
    * @return the application datasource bean corresponding with the current Spring Profile.
    */
    @Bean
    public abstract DataSource dataSource();

    /**
    * Defines the Hibernate session factory bean.
    * 
    * @return the {@code LocalSessionFactoryBean}.
    */
    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { HIBERNATE_PACKAGE_TO_SCAN });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    /**
    * Defines the bean allowing to Hibernate to support the transaction handling mechanism.
    * 
    * @return the {@code HibernateTransactionManager}.
    */
    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory().getObject());
        return txManager;
    }

    // ************************** PROTECTED METHODS **************************

    // ...

    // ************************** PRIVATE METHODS **************************

    // ...
}

I tried to run the application with the following commands with the same result:

我尝试使用以下命令运行应用程序,结果相同:

java -jar archibald-basket-handler-1.0-SNAPSHOT.jar --spring.profiles.active=dev

java -jar -Dspring.profiles.active=dev archibald-basket-handler-1.0-SNAPSHOT.jar

Concretely, the bean "sessionFactory" is not instanciated and cannot be injected into my GenericDaoImplclass...

具体来说,bean“ sessionFactory”未实例化,无法注入到我的GenericDaoImpl类中...

The stacktrace:

堆栈跟踪:

java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
        at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'basketDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory fr.ina.archibald.dao.impl.GenericDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:304)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:648)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:898)
        at fr.ina.archibald.basket.loader.BasketHandlerLoader.main(BasketHandlerLoader.java:30)
        ... 6 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory fr.ina.archibald.dao.impl.GenericDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
        ... 21 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.     Dependency annotations: {@javax.inject.Inject()}
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
        ... 23 more

I use the Spring Boot 1.0.2.RELEASE without the Spring Boot parent POM. I just defines this on the POM :

我使用没有 Spring Boot 父 POM 的 Spring Boot 1.0.2.RELEASE。我只是在 POM 上定义了这个:

<dependencyManagement>
    <dependency>
        <!-- Import dependency management from Spring Boot -->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>${org.springframework.boot.version}</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
</dependencyManagement>

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <mainClass>${start-class}</mainClass>
    </configuration>
</plugin>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-integration</artifactId>
    <version>${org.springframework.boot.version}</version>
</dependency>

Do you have some ideas?

你有什么想法吗?

Thanks a lot!!

非常感谢!!

采纳答案by Phil Webb

I think you need to @Importyour @Configurationclass directly or use the @ComponentScanannotation. You initial example that uses ClassPathXmlApplicationContextwill work because the XML processing happens early, and the <component-scan>will find your @Configurationclasses before they are processed.

我认为您需要直接到@Import您的@Configuration班级或使用@ComponentScan注释。您使用的初始示例ClassPathXmlApplicationContext将起作用,因为 XML 处理发生得较早,并且<component-scan>@Configuration在处理它们之前找到您的类。

With the second example SpringApplicationhas already started processing your @Configurationclasses and the XML is loaded via @ImportResource. By this time it is not possible for the XML <component-scan>to add more @Configuration.

第二个示例SpringApplication已经开始处理您的@Configuration类,并且 XML 是通过@ImportResource. 到这个时候,XML 不可能<component-scan>添加更多@Configuration

Sort answer: Try @ComonentScanon your BasketHandlerLoaderclass.

排序答案:试试@ComonentScan你的BasketHandlerLoader课。

回答by Didasko

Great!!! It works! A big big thank you Phil (for the solution and the explanations!) :-)

伟大的!!!有用!非常感谢 Phil(解决方案和解释!):-)

@Configuration
@ImportResource("classpath:config/spring/spring-archibald-basket-handler-context.xml")
@ComponentScan(basePackages = { "fr.ina.archibald.dao.config.persistence" }, includeFilters = @ComponentScan.Filter(value = Component.class, type = FilterType.ANNOTATION))
public class BasketHandlerLoader {

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