Reference documents: https://blog.csdn.net/BinshaoNo_1/article/details/85005935?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
Spring for Java configuration is achieved (here refer to Bowen through @Configuration and @Bean two notes https://blog.csdn.net/qq_41623154/article/details/104654953 , property injection on springboot, there are detailed explain):
@Configuration can act on any class that represents the class is a class configuration, in fact equivalent to a xml configuration file.
@Bean act on the method, in fact, equivalent xml configuration file bean, represents the creation of a Bean, return value type represents the type of Bean, Bean's method name indicates that the ID method.
In Spring3.0, @ Configuration arranged for defining classes, corresponding to the xml configuration file in springboot project to replace xml configuration file. Internal class annotated with one or more methods @Bean annotations, these methods will be scanned or AnnotationConfigWebApplicationContext AnnotationConfigApplicationContext class, and used to construct bea defined initialization spring containers.
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/","/index.html","/login","/userLogin","/static/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
/*设置默认跳转的请求视图*/
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
registry.addViewController("/login").setViewName("login");
registry.addViewController("/main.html").setViewName("main");
}
}
Precautions: @Configuration annotation configuration class has the following requirements:
- Configuration class is final not;
- Configuration class can not be anonymous class;
- Configuration class nested class must be static;
@Configuration marked on the class, such as a spring corresponding to the xml configuration file <beans>
, function as: a container disposed spring (application context)
to sum up
@Configuation equivalent to <Beans> </ Beans>
@Bean equivalent to <Bean> </ Bean>
@ComponentScan等价于<context:component-scan base-package=”com.study.mapper”/>