According to official doc:
Annotation Type Configuration
Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions...
@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..
But i can also use @Configuration annotation without @Import. I have tested the code listed below and it works as expected. So what is the purpose to use @Import?
DispatcherServletInitializer
public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
WebMvcConfigurerAdapter
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "package.name" })
// @Import(OptionalConfig.class)
public class WebConfig extends WebMvcConfigurerAdapter {
// ...
}
OptionalConfig
@Configuration
public class OptionalConfig {
@Bean(name = "myClass")
public MyClass myClass() {
return new MyClass();
}
}
Service
@Service
public class MyServiceImpl implements MyService {
@Autowired
private MyClass myClass; // yes, it works
// ...
}