Last Updated on 06 July 2023   |   Print Email
In this Spring annotations series, I’d like to help you understand the meaning, purpose and usage of the @Configurationannotation in Spring framework with various code examples.Basically, you use the @Configuration annotation to indicate that the annotated class declares one or more @Bean methods that return objects maybe processed by Spring container to generate bean definitions and service requests for those beans at runtime. The declared beans will be managed in the application context, thus eligible for used by other objects via dependency injection.A @Configuration class usually defines the configuration aspects of an application, such as datasource, transaction manager, resource handler, view resolver, security, etc.Let’s see a simplest example. Say, we have the following class:
package net.codejava;
public class MyClass {
public String getStuff() {
return "Awesome stuff";
}
}
And this is a configuration class:
package net.codejava;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyClass myBean() {
return new MyClass();
}
}
You see, this class is marked as @Configuration and it declares the method myBean() that returns an object of type MyClass. When Spring container finds this class (via classpath scanning), it will put a bean of type MyClass with the name myBean in the application context. Then it’s possible to inject this bean in another class, as shown below:
package net.codejava;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Autowired MyClass myBean;
public void doStuff() {
String stuff = myBean.getStuff();
}
}
Optional Elements (Parameters)
The @Configuration annotation can have 3 optional parameters:
enforceUniqueMethods: a boolean value that specifies whether @Bean methods need to have unique method names, raising an exception otherwise in order to prevent accidental overloading. Default is true.
proxyBeanMethods: a boolean value that specifies whether @Bean methods should get proxied in order to enforce bean lifecycle behavior, e.g. to return shared singleton bean instances even in case of direct @Bean method calls in user code. Default is true.
value: a String that explicitly specifies the name of the Spring bean definition associated with the @Configuration class. If left unspecified (the common case), a bean name will be automatically generated.
Below is another example:
@Configuration(value = "config1", proxyBeanMethods = false,
enforceUniqueMethods = false)
public class AppConfig {
...
}
Note that there can be multiple @Configuration classes in an application.Now, let’s see some real life code examples that uses @Configuration annotations.This is a configuration class that configures Spring MVC view resolver and resource handler:
@Configuration
@ComponentScan(basePackages="net.codejava.spring")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
And below is a configuration class for data source and DAO:
@Configuration
public class DAOConfig {
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/contactdb");
dataSource.setUsername("root");
dataSource.setPassword("pass");
return dataSource;
}
@Bean
public ContactDAO getContactDAO() {
return new ContactDAOImpl(getDataSource());
}
}
And the following code example is a typical configuration class for Spring Security:
@Configuration
public class SecurityConfiguration {
@Bean
public UserDetailsService userDetailsService() {
...
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
...
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
...
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
...
}
}
That’s my explanation and code examples about the @Configuration annotation in Spring framework. I hope you found this article helpful.Watch the following video to see the coding in action: Reference:Annotation Interface Configuration (Spring Docs)
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments