springBoot 修行之路1
1.springBoot的注解
为啥要先谈springboot注解呢,主要是因为springBoot的配置少,通过几个注解就可以完成好多spring的加载
1.1启动类核心注解@SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。其中@ComponentScan让spring Boot扫描到Configuration类并把它加入到程序上下文。
@Configuration 等同于spring的XML配置文件;使用Java代码可以检查类型安全。
@EnableAutoConfiguration 开启自动配置。
@ComponentScan 组件扫描,可自动发现和装配一些Bean。
@Component可配合CommandLineRunner使用,在程序启动后执行一些基础任务
2.springboot核心原理
通过springboot的核心注解@SpringBootApplication来完成自动装配启动IOC容器,自动扫描配置类和文件,这一点主要是记住上面三个注解的作用;
@SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration
@EnableAutoConfiguration 开启自动配置
@ComponentScan :扫描bean,配置文件
@Configuration 相当于xml配置文件
3.springboot跨域问题之CROS
最简单的方法是
使用@CrossOrigin
@CrossOrigin(origins = "http://192.1.1.1.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class ProjectController {
@GetMapping("/{id}")
public Project retrieve(@PathVariable Long id) {
// ...
}
@DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
其中@CrossOrigin中的2个参数:
origins : 允许可访问的域列表
maxAge:准备响应前的缓存持续的最大时间(以秒为单位)。
2全局CORS配置
除了细粒度、基于注释的配置之外,您还可能需要定义一些全局CORS配置。这类似于使用筛选器,但可以声明为Spring MVC并结合细粒度@CrossOrigin配置。默认情况下,所有origins and GET, HEAD and POST methods是允许的。
JavaConfig
使整个应用程序的CORS简化为:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
如果您正在使用Spring Boot,建议将WebMvcConfigurer bean声明如下:
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
您可以轻松地更改任何属性,以及仅将此CORS配置应用到特定的路径模式:
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
其他还有通过过滤器filter,或者xml配置等