spring-boot基礎

什么是Spring Boot

Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發(fā)過程嘲碱。使用Spring Boot框架可以做到專注于Spring應用的開發(fā)充易,無須過多關(guān)注樣板化的配置。
在Spring Boot框架中,使用“約定優(yōu)于配置(Convention Over Configuration员咽,COC)”的理念根暑。

優(yōu)點

(1)使編碼變得簡單:推薦使用注解力试。
(2)使配置變得快捷:具有自動配置、快速構(gòu)建項目排嫌、快速集成第三方技術(shù)的能力畸裳。
(3)使部署變得簡便:內(nèi)嵌Tomcat、Jetty等Web容器淳地。
(4)使監(jiān)控變得容易:自帶項目監(jiān)控怖糊。

@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
實現(xiàn) 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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末扰魂,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子蕴茴,更是在濱河造成了極大的恐慌劝评,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件倦淀,死亡現(xiàn)場離奇詭異蒋畜,居然都是意外死亡,警方通過查閱死者的電腦和手機撞叽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門姻成,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人能扒,你說我怎么就攤上這事佣渴。” “怎么了初斑?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵辛润,是天一觀的道長。 經(jīng)常有香客問我,道長砂竖,這世上最難降的妖魔是什么真椿? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮乎澄,結(jié)果婚禮上突硝,老公的妹妹穿的比我還像新娘。我一直安慰自己置济,他們只是感情好解恰,可當我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著浙于,像睡著了一般护盈。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上羞酗,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天腐宋,我揣著相機與錄音,去河邊找鬼檀轨。 笑死胸竞,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的参萄。 我是一名探鬼主播卫枝,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼拧揽!你這毒婦竟也來了剃盾?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤淤袜,失蹤者是張志新(化名)和其女友劉穎痒谴,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體铡羡,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡积蔚,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了烦周。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片尽爆。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖读慎,靈堂內(nèi)的尸體忽然破棺而出漱贱,到底是詐尸還是另有隱情,我是刑警寧澤夭委,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布幅狮,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏崇摄。R本人自食惡果不足惜擎值,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望逐抑。 院中可真熱鬧鸠儿,春花似錦、人聲如沸厕氨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽腐巢。三九已至品追,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間冯丙,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工遭京, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留胃惜,地道東北人。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓哪雕,卻偏偏與公主長得像船殉,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子斯嚎,可洞房花燭夜當晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內(nèi)容