Spring无法在配置文件“ dev”中初始化bean

时间:2018-09-13 08:42:27

标签: java spring javabeans profile

我的代码抛出此异常:

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'Unknown' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:686)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)
    at core.Main.main(Main.java:38)

我正在使用混合配置-基于XML和注解:

开发环境:

<beans profile="dev">

    <context:component-scan base-package="core"/>
    <context:annotation-config/>

    <import resource="classpath:beans/beans.xml"/>

</beans>

Beans.xml上下文:包含以XML初始化的其他bean-在那里没有使用注释。

<beans profile="dev,default">
   <bean ...
   <bean ...
</beans>

这是有问题的配置(请注意以下注释):

@Configuration
@Profile({"dev"})
public class MyConfig {

    @Bean(value="Unknown")
    @Description("Bean for unknown user")
    public User getUnknownUser() {
        User user = new User(-1);
        user.setUsername("Unknown");
        return user;
    }
}

Spring正确初始化了XML定义的bean-这些bean在default配置文件中。 dev个人资料中只有未知的用户。

主类:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("dev.xml");
applicationContext.getEnvironment().acceptsProfiles("dev");
User unknown = (User)applicationContext.getBean("Unknown");
LOGGER.info(unknown.toString());

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

我发现我错过了这一行:

    applicationContext.refresh();

现在工作,谢谢