Adam Ostrožlík
Adam Ostrožlík

Reputation: 1416

Spring cannot initialize bean in profile "dev"

My code throws this exception:

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)

I am using mixed configuration - XML and Annotation based:

Dev context:

<beans profile="dev">

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

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

</beans>

Beans.xml context: contains other beans which are initialized in XML - no annotations used there.

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

And here is problematic Configuration (please note the comment below):

@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 correctly initializes beans defined in XML - these beans is in default profile. Only the unknown user is in dev profile.

Main class:

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

Thanks for your help

Upvotes: 0

Views: 900

Answers (1)

Adam Ostrožl&#237;k
Adam Ostrožl&#237;k

Reputation: 1416

I have discovered that i was missing this line:

    applicationContext.refresh();

Works now, thanks

Upvotes: 1

Related Questions