user79301
user79301

Reputation: 13

When is a spring @configuration class executed?

So when exactly is a @configuration class executed and what is the scope of it?

Is it one per session? One per entire application? But my next question is where does the bean return to after executing? Maybe this code will help you understand better what I mean.

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
   @Autowired
   Environment env;

   @Bean
   public DBConnection testBean() {
     DBConnection testBean = new DBConnection();
       testBean.setName(env.getProperty("testbean.name"));
       return testBean;
   }
}

So more or less when would this DBConnection be valid/initiated?

Upvotes: 0

Views: 1635

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280030

A @Configuration annotated class is just that, a class annotated with the @Configuration annotation. It does nothing on its own.

You need something to evaluate and process the class. This is done through bootstrapping. You have three options

  1. Register the class with an AnnotationConfigApplicationContext instance.
  2. Specify the class as a <bean> in XML configuration with the corresponding XML-enabled ApplicationContext.
  3. Place the class in a package that is component-scanned.

These options are detailed in the javadoc and, in a lot more detail, in the Spring IOC documentation.

Beans you declare in the @Configuration class live as long as their corresponding scope. Your testBean bean has singleton scope and therefore lives as long as the containing ApplicationContext.

Upvotes: 2

Related Questions