美文网首页
spring-boot基础

spring-boot基础

作者: shoyu666 | 来源:发表于2022-04-09 11:57 被阅读0次
    什么是Spring Boot

    Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。使用Spring Boot框架可以做到专注于Spring应用的开发,无须过多关注样板化的配置。
    在Spring Boot框架中,使用“约定优于配置(Convention Over Configuration,COC)”的理念。

    优点

    (1)使编码变得简单:推荐使用注解。
    (2)使配置变得快捷:具有自动配置、快速构建项目、快速集成第三方技术的能力。
    (3)使部署变得简便:内嵌Tomcat、Jetty等Web容器。
    (4)使监控变得容易:自带项目监控。

    @SpringBootApplication

    @SpringBootApplication
    @Slf4j
    public class HelloApplication {
        public static void main(String[] args) {
            SpringApplication.run(HelloApplication.class, args);
        }
    }
    
    
    @SpringBootConfiguration
    @EnableAutoConfiguration
    @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
            @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
    public @interface SpringBootApplication {
    
    
    @Configuration
    public @interface SpringBootConfiguration {
    
    @Configuration(Spring的注解,不是SpringBoot)

    注解的作用:声明一个类为配置类,用于取代bean.xml配置文件注册bean对象

    设置端口号

    server.port=8888

    @Value

        @Value("${spring.profiles.active}")
        private String activeProfile;
    

    @ConfigurationProperties

    @ConfigurationProperties(
            prefix = "jnt.id"
    )
    @Component
    @Data
    public class JntIDProperties {
    
        @NestedConfigurationProperty
        private JntIDProperties.CreateOrder createOrder;
    
        @NestedConfigurationProperty
        private JntIDProperties.Track tracking;
    
        @NestedConfigurationProperty
        private JntIDProperties.ConsignmentNote consignmentNote;
    

    @PropertySource

    //a.properties
    a.msg=hello a
    //b.properties
    b.msg=hello b
    @Controller
    @PropertySource("a.properties","b.properties")
    public class MyController{
        @Value("${a.msg}")
         public String aMsg;
        @Value("${b.msg}")
         public String bMsg;
    }
    

    Spring Boot的自动配置原理

    image.png
    public final class SpringFactoriesLoader {
    
        /**
         * The location to look for factories.
         * <p>Can be present in multiple JAR files.
         */
        public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
    

    @SpringBootApplication注解通过使用@EnableAutoConfiguration注解自动配置的原理是:从classpath中搜索所有META-INF/spring.factories配置文件,并将其中org.springframework.boot.autoconfigure.EnableAutoConfiguration对应的配置项通过Java反射机制进行实例化,然后汇总并加载到Spring的IoC容器。

    条件注解(@ConditionalXXX)

    image.png

    自定义条件

    public class MyCondition implements Condition {
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            return false;
        }
    }
    

    mybatis-spring-boot-starter

    image.png
    #spring.factories
    # Auto Configure
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration,\
    org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
    
    @ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
    @ConditionalOnSingleCandidate(DataSource.class)
    @EnableConfigurationProperties(MybatisProperties.class)
    //控制加载顺序
    @AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class }) 
    public class MybatisAutoConfiguration implements InitializingBean {
    

    自定义starter

    添加spring.factories
    #spring.factories
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=shop.xxx.common.env.configuration.ApplicationReadyListener
    
    实现 ApplicationReadyListener
    @Configuration
    public class ApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {
    

    spring-boot redis 集成

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.0.4.RELEASE</version>
    </dependency>
    
    spring:
        redis:
            database: 0
            host: 127.0.0.1
            port: 6379
            jedis:
              pool:
                max-active: 100
                max-idle: 10
                max-wait: 100000
            timeout: 5000
    

    可选

    @Configuration
    @ConditionalOnClass(RedisOperations.class)
    @EnableConfigurationProperties(RedisProperties.class)
    public class RedisConfig {
    
    
        @Bean
        @ConditionalOnMissingBean(name = "redisTemplate")
        public RedisTemplate<Object, Object> redisTemplate(
                RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate<Object, Object> template = new RedisTemplate<>();
            //使用fastjson序列化
            FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
            // value值的序列化采用fastJsonRedisSerializer
            template.setValueSerializer(fastJsonRedisSerializer);
            template.setHashValueSerializer(fastJsonRedisSerializer);
            // key的序列化采用StringRedisSerializer
            template.setKeySerializer(new StringRedisSerializer());
            template.setHashKeySerializer(new StringRedisSerializer());
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }
    
        @Bean
        @ConditionalOnMissingBean(StringRedisTemplate.class)
        public StringRedisTemplate stringRedisTemplate(
                RedisConnectionFactory redisConnectionFactory) {
            StringRedisTemplate template = new StringRedisTemplate();
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }
    
    }
    

    spring aop

    @Aspect
    @Component
    @Slf4j
    public class OAuthAspect {
    
        @Pointcut(value = "@annotation(shop.melf.social.server.core.facebbook.FbOAuthAnnotation)")
        public void servicePointcut() {
        }
    
    
        @Around(value = "servicePointcut()")
        @SneakyThrows
        public Object bossAround(ProceedingJoinPoint joinPoint) {
    
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    public @interface FbOAuthAnnotation {
        boolean pageAccessToken() default false;
        boolean refreshToken() default false;
    }
    
        @SneakyThrows
        @FbOAuthAnnotation(pageAccessToken = true)
        public LiveVideoResp lives(FbEnv param, String status) {
            LiveVideoReq req = new LiveVideoReq();
            req.setStatus(status);
            req.setFbPageId(param.getFbPageId());
            LiveVideoResp result = client.execute(req, param.getPageAccessToken(redisService, param), true);
            OAuthAspect.autCheck2(param, result,req);
            return result;
        }
    

    ApplicationEvent & ApplicationListener

    public class DemoEvent extends ApplicationEvent {
     
     private static final long serialVersionUID = 1L;
     private String msg;
     
     public DemoEvnet(Object source, String msg) {
      super(source);
      this.msg = msg;
     }
     
     public String getMsg() {
      return msg;
     }
     
     public void setMsg(String msg) {
      this.msg = msg;
     }
    }
    
    @Component
    public class DemoListener implements ApplicationListener<DemoEvent> {
     
     public void onApplicationEvent(DemoEvent event) {
      String msg = event.getMsg();
      System.out.println("接收到了消息:" + msg);
     }
    }
    
    @Component
    public class DemoPublisher {
     @Autowired
     ApplicationContext applicationContext;
     
     public void publish(String msg) {
      applicaionContext.publishEvent(new DemoEvent(this, msg));
     }
    }
    
    @Configuration
    @EnableAsync
    public class AsyncTaskExecutorConfig {
        @Bean
        public Executor asyncTaskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(5);
            executor.setMaxPoolSize(5);
            executor.setQueueCapacity(200);
            executor.setThreadNamePrefix("async-erp-task-");
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            executor.initialize();
            return executor;
        }
    }
    

    protocol-buffers

    https://developers.google.com/protocol-buffers

    image.png

    相关文章

      网友评论

          本文标题:spring-boot基础

          本文链接:https://www.haomeiwen.com/subject/yohpsrtx.html