SpringBoot的那些事

一、配置环境方面:

配置文件可分为.properties和.yml两种格式

配置文件可分为dev/test/prod三种环境

通过spring.profiles.active或者spring.profiles.default来指定生产环境,默认的application.yml依旧会被读取,同时还会读取激活的配置文件,被指定激活的配置文件属性会覆盖application.yml的属性

在@Configuration配置类中使用@Profile("")指定环境,则可以根据不同环境决定是否产生该Bean

在单元测试中在方法通过@ActiveProfiles来指定运行该单元测试需要启动的配置文件。

 

二、开发使用方面:

1.装配相关:

  • @Primary注解:与@Bean或者@Component一起使用,在遇到多个装配实例时默认装配带有@Pramary的实例,该注解具有唯一性
  • @Qualifier("")与@AutoWired配合使用,同时对type和名称进行限定装配  -->>>@Resource("")  -->>@Inject()+@Named
  • @Scope(ConfigurableBeanFactory.xxxx),singleton:单例,默认;prototype:每次注入new一个新的实例;session,会话;request:每次请求;
  • @PropertySource("classpath:/com/*...../application.properties"),

        @Autowired

         Environment env;

         env.getProperty(key)得到配置文件中的值

         @Value("${key}")  String value:通过@Value注解获取配置文件中的值,@Value不能直接作用于静态变量

  •     SpEL表达式

         #{T(System).currentTimeMillis()},T()将其视为一个java类型

        #{student.age}:获取对象属性值

        #{systemProperties[ ' redis.poo.max ' ]},获取配置文件值,配合@Value注解使用,类似${"..."}

2.Web中的Spring

  • spring-security

        1)继承自WebSecurityConfigurerAdapter,打上注解:@EnableWebMvcSecurity,@Configuration

        2)重写三个configure方法

              configure(WebSecurity)   配置Spring Security的Filter链

              configure(HttpSecurity  http)    配置如何通过拦截器保护请求

              configure(AuthenticationManagerBuilder auth)    配置user_detail服务

        3)内存配置:auth.withUser("").password("").roles("xx").and(),and()用于连接配置,roles("xx")等价于authorities("ROLE_xx")

        4)拦截请求:http.authorizeRequests().antMatchers("/student/**").authenticated() //Ant风格请求认证,未登录则进入登陆页面

                                                                             .regexMatchers("/student/.*").authenticated()  //正则表达式风格

                                                                             .anyRequest().permitAll();   //放过所有请求

                                         .and()

                                          .requiresChannel().antMatchers("/").requiresSecure();  //需要HTTPS  requiresInecure()  https---》http

3.springboot async异步

  •     使用默认的线程池

          1)配置类或者启动类上配置@EnableAsync开启异步注解

          2)在实现方法上加上@Async实现默认的线程池调用异步

  • 自定义线程池

           1)自定义线程池配置类实现AsyncConfigure,注入到sring容器,代码如下:

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    @Bean("myAsync")
    @Override
    public Executor getAsyncExecutor() {
        System.out.println("使用自定义线程池");
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

            2)在异步方法上加上@Async(value = "myAsync")

4.条件注解

        1)创建条件注解类实现Condition

public class DevEnvCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        //通过conditionContext获取相关数据,例如:
        Environment environment = conditionContext.getEnvironment();
        //根据evironment获取相关数据进行判断,返回boolean
        return true;
    }
}

        2)配合@Bean注解使用@Conditional(DevEnvCondition .class)进行条件注入,如果为true则实例化该Bean。

5.Springboot自定义启动图案

       1)在src/main/resources下新建一个banner.txt

       2)在http://patorjk.com/software/taag网站生成字符,复制到banner.txt中即可。

       3)关闭Banner,代码如下:

public static void main( String[] args )
{
   
    SpringApplication springApplication = new SpringApplication(App.class);
    springApplication.setBannerMode(Banner.Mode.OFF);
    springApplication.run(App.class);
}

6.自动注入配置变量

  • 定义一个映射实体,加上@Component和@ConfigurationProperties(prefix = "配置文件前缀",locations="classthpath:配置文件地址")
  • 在要用的地方使用@Autowired注入实体就行了,然后使用getters进行操作

7.WebSocket的使用

  • 添加依赖包
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  • 编写WebSocket配置类
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    /**
     * 注册端点,发布或者订阅消息的时候需要连接此端点
     * setAllowedOrigins 非必须,*表示允许其他域进行连接
     * withSockJS  表示开始sockejs支持
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/endpoint-websocket").setAllowedOrigins("*").withSockJS();
    }

    /**
     * 配置消息代理(中介)
     * enableSimpleBroker 服务端推送给客户端的路径前缀
     * setApplicationDestinationPrefixes  客户端发送数据给服务器端的一个前缀
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/sendToClient");
        registry.setApplicationDestinationPrefixes("/sendToServer");
    }
}
  • 编写Controller
@RestController
public class WebSocketController {

    @MessageMapping("/getWSMessage")
    @SendTo("/sendToClient/response")
    public String testWebSocket(String message){
        return "我是服务器:"+message;
    }
}

7.springboot打包成war包

  • pom文件修改为<packaging>war</packaging>
  • 增加依赖覆盖默认内嵌的Tomcat
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>   <!--只参与编译、测试,不参与打包-->
</dependency>
  • 新增类
public class ServlrtInitializer extends SpringBootServletInitializer {
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(App.class);  //主启动类
    }
}

为什么继承该类,SpringBootServletInitializer源码注释:

Note that a WebApplicationInitializer is only needed if you are building a war file and deploying it. 

If you prefer to run an embedded web server then you won't need this at all.

注意,如果您正在构建WAR文件并部署它,则需要WebApplicationInitializer。

    

 

                                   

 

     

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值