- Org springframework config java annotation configuration
- Bootstrapping @Configuration classes
- Via AnnotationConfigApplicationContext
- Via Spring XML
- Via component scanning
- Working with externalized values
- Using the Environment API
- Using the @Value annotation
- Composing @Configuration classes
- With the @Import annotation
- With the @Profile annotation
- With Spring XML using the @ImportResource annotation
- With nested @Configuration classes
- Configuring lazy initialization
- Testing support for @Configuration classes
- Enabling built-in Spring features using @Enable annotations
- Constraints when authoring @Configuration classes
- Optional Element Summary
- Element Detail
- value
- Annotation-based Container Configuration
Org springframework config java annotation configuration
Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime, for example:
@Configuration public class AppConfig < @Bean public MyBean myBean() < // instantiate, configure and return bean . >>
Bootstrapping @Configuration classes
Via AnnotationConfigApplicationContext
@Configuration classes are typically bootstrapped using either AnnotationConfigApplicationContext or its web-capable variant, AnnotationConfigWebApplicationContext . A simple example with the former follows:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class); ctx.refresh(); MyBean myBean = ctx.getBean(MyBean.class); // use myBean .
See AnnotationConfigApplicationContext Javadoc for further details and see AnnotationConfigWebApplicationContext for web.xml configuration instructions.
Via Spring XML
As an alternative to registering @Configuration classes directly against an AnnotationConfigApplicationContext , @Configuration classes may be declared as normal
In the example above,
Via component scanning
@Configuration is meta-annotated with @Component , therefore @Configuration classes are candidates for component scanning (typically using Spring XML’s element) and therefore may also take advantage of @Autowired / @Inject like any regular @Component . In particular, if a single constructor is present autowiring semantics will be applied transparently:
@Configuration public class AppConfig < private final SomeBean someBean; public AppConfig(SomeBean someBean) < this.someBean = someBean; >// @Bean definition using "SomeBean" >
@Configuration classes may not only be bootstrapped using component scanning, but may also themselves configure component scanning using the @ComponentScan annotation:
@Configuration @ComponentScan("com.acme.app.services") public class AppConfig < // various @Bean definitions . >
Working with externalized values
Using the Environment API
Externalized values may be looked up by injecting the Spring Environment into a @Configuration class the usual (e.g. using the @Autowired annotation):
@Configuration public class AppConfig < @Autowired Environment env; @Bean public MyBean myBean() < MyBean myBean = new MyBean(); myBean.setName(env.getProperty("bean.name")); return myBean; >>
Properties resolved through the Environment reside in one or more «property source» objects, and @Configuration classes may contribute property sources to the Environment object using the @PropertySources annotation:
@Configuration @PropertySource("classpath:/com/acme/app.properties") public class AppConfig < @Inject Environment env; @Bean public MyBean myBean() < return new MyBean(env.getProperty("bean.name")); >>
Using the @Value annotation
@Configuration @PropertySource("classpath:/com/acme/app.properties") public class AppConfig < @Value("$") String beanName; @Bean public MyBean myBean() < return new MyBean(beanName); >>
This approach is most useful when using Spring’s PropertySourcesPlaceholderConfigurer , usually enabled via XML with . See the section below on composing @Configuration classes with Spring XML using @ImportResource , see @Value Javadoc, and see @Bean Javadoc for details on working with BeanFactoryPostProcessor types such as PropertySourcesPlaceholderConfigurer .
Composing @Configuration classes
With the @Import annotation
@Configuration classes may be composed using the @Import annotation, not unlike the way that works in Spring XML. Because @Configuration objects are managed as Spring beans within the container, imported configurations may be injected the usual way (e.g. via constructor injection):
@Configuration public class DatabaseConfig < @Bean public DataSource dataSource() < // instantiate, configure and return DataSource >> @Configuration @Import(DatabaseConfig.class) public class AppConfig < private final DatabaseConfig dataConfig; public AppConfig(DatabaseConfig dataConfig) < this.dataConfig = dataConfig; >@Bean public MyBean myBean() < // reference the dataSource() bean method return new MyBean(dataConfig.dataSource()); >>
Now both AppConfig and the imported DatabaseConfig can be bootstrapped by registering only AppConfig against the Spring context:
new AnnotationConfigApplicationContext(AppConfig.class);
With the @Profile annotation
@Configuration classes may be marked with the @Profile annotation to indicate they should be processed only if a given profile or profiles are active:
@Profile("embedded") @Configuration public class EmbeddedDatabaseConfig < @Bean public DataSource dataSource() < // instantiate, configure and return embedded DataSource >> @Profile("production") @Configuration public class ProductionDatabaseConfig < @Bean public DataSource dataSource() < // instantiate, configure and return production DataSource >>
With Spring XML using the @ImportResource annotation
As mentioned above, @Configuration classes may be declared as regular Spring
@Configuration @ImportResource("classpath:/com/acme/database-config.xml") public class AppConfig < @Inject DataSource dataSource; // from XML @Bean public MyBean myBean() < // inject the XML-defined dataSource bean return new MyBean(this.dataSource); >>
With nested @Configuration classes
@Configuration public class AppConfig < @Inject DataSource dataSource; @Bean public MyBean myBean() < return new MyBean(dataSource); >@Configuration static class DatabaseConfig < @Bean DataSource dataSource() < return new EmbeddedDatabaseBuilder().build(); >> >
When bootstrapping such an arrangement, only AppConfig need be registered against the application context. By virtue of being a nested @Configuration class, DatabaseConfig will be registered automatically. This avoids the need to use an @Import annotation when the relationship between AppConfig DatabaseConfig is already implicitly clear. Note also that nested @Configuration classes can be used to good effect with the @Profile annotation to provide two options of the same bean to the enclosing @Configuration class.
Configuring lazy initialization
By default, @Bean methods will be eagerly instantiated at container bootstrap time. To avoid this, @Configuration may be used in conjunction with the @Lazy annotation to indicate that all @Bean methods declared within the class are by default lazily initialized. Note that @Lazy may be used on individual @Bean methods as well.
Testing support for @Configuration classes
The Spring TestContext framework available in the spring-test module provides the @ContextConfiguration annotation, which as of Spring 3.1 can accept an array of @Configuration Class objects:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes=) public class MyTests < @Autowired MyBean myBean; @Autowired DataSource dataSource; @Test public void test() < // assertions against myBean . >>
Enabling built-in Spring features using @Enable annotations
Spring features such as asynchronous method execution, scheduled task execution, annotation driven transaction management, and even Spring MVC can be enabled and configured from @Configuration classes using their respective » @Enable » annotations. See @EnableAsync , @EnableScheduling , @EnableTransactionManagement , @EnableAspectJAutoProxy , and @EnableWebMvc for details.
Constraints when authoring @Configuration classes
- Configuration classes must be provided as classes (i.e. not as instances returned from factory methods), allowing for runtime enhancements through a generated subclass.
- Configuration classes must be non-final.
- Configuration classes must be non-local (i.e. may not be declared within a method).
- Any nested configuration classes must be declared as static .
- @Bean methods may not in turn create further configuration classes (any such instances will be treated as regular beans, with their configuration annotations remaining undetected).
Optional Element Summary
Element Detail
value
public abstract java.lang.String value
Explicitly specify the name of the Spring bean definition associated with this Configuration class. If left unspecified (the common case), a bean name will be automatically generated. The custom name applies only if the Configuration class is picked up via component scanning or supplied directly to a AnnotationConfigApplicationContext . If the Configuration class is registered as a traditional XML bean definition, the name/id of the bean element will take precedence.
Annotation-based Container Configuration
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML. The short answer is “it depends.” The long answer is that each approach has its pros and cons, and, usually, it is up to the developer to decide which strategy suits them better. Due to the way they are defined, annotations provide a lot of context in their declaration, leading to shorter and more concise configuration. However, XML excels at wiring up components without touching their source code or recompiling them. Some developers prefer having the wiring close to the source while others argue that annotated classes are no longer POJOs and, furthermore, that the configuration becomes decentralized and harder to control.
No matter the choice, Spring can accommodate both styles and even mix them together. It is worth pointing out that through its JavaConfig option, Spring lets annotations be used in a non-invasive way, without touching the target components’ source code and that, in terms of tooling, all configuration styles are supported by Spring Tools for Eclipse, Visual Studio Code, and Theia.
An alternative to XML setup is provided by annotation-based configuration, which relies on bytecode metadata for wiring up components instead of XML declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration. As mentioned in Example: The AutowiredAnnotationBeanPostProcessor , using a BeanPostProcessor in conjunction with annotations is a common means of extending the Spring IoC container. For example, the @Autowired annotation provides the same capabilities as described in Autowiring Collaborators but with more fine-grained control and wider applicability. In addition, Spring provides support for JSR-250 annotations, such as @PostConstruct and @PreDestroy , as well as support for JSR-330 (Dependency Injection for Java) annotations contained in the jakarta.inject package such as @Inject and @Named . Details about those annotations can be found in the relevant section.
Annotation injection is performed before XML injection. Thus, the XML configuration overrides the annotations for properties wired through both approaches.
As always, you can register the post-processors as individual bean definitions, but they can also be implicitly registered by including the following tag in an XML-based Spring configuration (notice the inclusion of the context namespace):
The element implicitly registers the following post-processors:
only looks for annotations on beans in the same application context in which it is defined. This means that, if you put in a WebApplicationContext for a DispatcherServlet , it only checks for @Autowired beans in your controllers, and not your services. See The DispatcherServlet for more information.
Apache®, Apache Tomcat®, Apache Kafka®, Apache Cassandra™, and Apache Geode™ are trademarks or registered trademarks of the Apache Software Foundation in the United States and/or other countries. Java™, Java™ SE, Java™ EE, and OpenJDK™ are trademarks of Oracle and/or its affiliates. Kubernetes® is a registered trademark of the Linux Foundation in the United States and other countries. Linux® is the registered trademark of Linus Torvalds in the United States and other countries. Windows® and Microsoft® Azure are registered trademarks of Microsoft Corporation. “AWS” and “Amazon Web Services” are trademarks or registered trademarks of Amazon.com Inc. or its affiliates. All other trademarks and copyrights are property of their respective owners and are only mentioned for informative purposes. Other names may be trademarks of their respective owners.