Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AnnotationConfigApplicationContext has not been refreshed yet - what's wrong?

Tags:

My very basic spring application stopped working and I can't understand what's happened. pom.xml:

<properties>     <spring.version>4.1.1.RELEASE</spring.version> </properties>  <dependencies>     <dependency>         <groupId>org.springframework</groupId>         <artifactId>spring-core</artifactId>         <version>${spring.version}</version>     </dependency>     <dependency>         <groupId>org.springframework</groupId>         <artifactId>spring-context</artifactId>         <version>${spring.version}</version>     </dependency> </dependencies> 

Config class:

@Configuration public class MyConfig {  @Bean public HelloWorld helloWorld() {          return new HelloWorld();     } } 

Bean class:

public class HelloWorld {     private String message;      public void setMessage(String message) {         this.message = message;     }     public String getMessage() {          return message;     } } 

Entry point of application:

public class MainApp { public static void main(String[] args) {     AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();     ctx.register(MyConfig.class);     HelloWorld bean = ctx.getBean(HelloWorld.class);     bean.setMessage("ladjfaj");     System.out.println(bean.getMessage()); } } 

And I'm getting an error

Exception in thread "main" java.lang.IllegalStateException: org.springframework.context.annotation.AnnotationConfigApplicationContext@6ebf8cf5 has not been refreshed yet at org.springframework.context.support.AbstractApplicationContext.assertBeanFactoryActive(AbstractApplicationContext.java:943) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:967) at com.nikolas.config.MainApp.main(MainApp.java:12)

like image 867
Nikolas Avatar asked Feb 09 '15 07:02

Nikolas


People also ask

How do I refresh application context in spring boot?

You can use: POST to /actuator/env to update the Environment and rebind @ConfigurationProperties and log levels. /actuator/refresh to re-load the boot strap context and refresh the @RefreshScope beans. /actuator/restart to close the ApplicationContext and restart it (disabled by default).

What is AnnotationConfigApplicationContext in spring?

AnnotationConfigApplicationContext is a standalone application context which accepts annotated classes as input. For instance, @Configuration or @Component . Beans can be looked up with scan or registered with register .


1 Answers

You have to call ctx.refresh() before you can call ctx.getBean(HelloWorld.class);

like image 184
Jens Avatar answered Sep 16 '22 15:09

Jens