• springboot学习章节代码-spring高级话题


    1、Spring Aware(获取Spring容器的服务)

    hi, i am guodaxia!
    test.txt
    package com.zhen.highlights_spring4.ch3.aware;
    
    import org.apache.commons.io.IOUtils;
    import org.springframework.beans.factory.BeanNameAware;
    import org.springframework.context.ResourceLoaderAware;
    import org.springframework.core.io.Resource;
    import org.springframework.core.io.ResourceLoader;
    import org.springframework.stereotype.Service;
    
    import java.io.IOException;
    
    /**
     * @author zhen
     * @Date 2018/7/2 10:49
     */
    @Service("awareService")
    public class AwareService implements BeanNameAware, ResourceLoaderAware {
        private String beanName;
        private ResourceLoader resourceLoader;
    
        @Override
        public void setBeanName(String beanName) {
            this.beanName = beanName;
        }
    
        @Override
        public void setResourceLoader(ResourceLoader resourceLoader) {
            this.resourceLoader = resourceLoader;
        }
    
        public void outputResult(){
            System.out.println("Bean的名称为:" + beanName);
            Resource resource = resourceLoader.getResource("classpath:/com/zhen/highlights_spring4/ch3/aware/test.txt");
            try{
                System.out.println("ResourceLoader加载的文件内容为:" + IOUtils.toString(resource.getInputStream()));
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    package com.zhen.highlights_spring4.ch3.aware;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @author zhen
     * @Date 2018/7/2 10:53
     */
    @Configuration
    @ComponentScan("com.zhen.highlights_spring4.ch3.aware")
    public class AwareConfig {
    }
    package com.zhen.highlights_spring4.ch3.aware;
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    /**
     * @author zhen
     * @Date 2018/7/2 10:54
     */
    public class Main {
        public static void main(String[] args){
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
    
            AwareService awareService = context.getBean(AwareService.class);
            awareService.outputResult();
    
            context.close();
        }
    }
    View Code

    2、多线程

    package com.zhen.highlights_spring4.ch3.taskexecutor;
    
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;
    
    /**
     * @author zhen
     * @Date 2018/7/2 11:02
     */
    @Service
    public class AsyncTaskService {
    
        @Async
        public void executeAsyncTask(Integer i){
            System.out.println("执行异步任务:" + i);
        }
    
        @Async
        public void executeAsyncTaskPlus(Integer i){
            System.out.println("执行异步任务+1:" + (i+1));
        }
    }
    package com.zhen.highlights_spring4.ch3.taskexecutor;
    
    import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.AsyncConfigurer;
    import org.springframework.scheduling.annotation.EnableAsync;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    
    import java.util.concurrent.Executor;
    
    /**
     * @author zhen
     * @Date 2018/7/2 10:57
     */
    @Configuration
    @ComponentScan("com.zhen.highlights_spring4.ch3.taskexecutor")
    @EnableAsync
    public class TaskExecutorConfig implements AsyncConfigurer {
    
        @Override
        public Executor getAsyncExecutor() {
            ThreadPoolTaskExecutor taskExcutor = new ThreadPoolTaskExecutor();
            taskExcutor.setCorePoolSize(5);
            taskExcutor.setMaxPoolSize(10);
            taskExcutor.setQueueCapacity(25);
            taskExcutor.initialize();
            return taskExcutor;
        }
    
        @Override
        public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
            return null;
        }
    }
    package com.zhen.highlights_spring4.ch3.taskexecutor;
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    /**
     * @author zhen
     * @Date 2018/7/2 11:05
     */
    public class Main {
        public static void main(String[] args){
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
    
            AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
    
            for(int i=0; i<10; i++){
                asyncTaskService.executeAsyncTask(i);
                asyncTaskService.executeAsyncTaskPlus(i);
            }
    
            context.close();
        }
    }
    View Code

    3、计划任务

    package com.zhen.highlights_spring4.ch3.taskscheduler;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Service;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
     * @author zhen
     * @Date 2018/7/2 14:59
     */
    @Service
    public class ScheduledTaskService {
    
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    
        @Scheduled(fixedRate = 5000)
        public void reportCurrentTime(){
            System.out.println("每隔5秒执行一次 " + dateFormat.format(new Date()));
        }
    
        @Scheduled(cron = "0 16 15 ? * *")
        public void fixTimeExcution(){
            System.out.println("在指定时间 " + dateFormat.format(new Date()) + "执行");
        }
    }
    package com.zhen.highlights_spring4.ch3.taskscheduler;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    /**
     * @author zhen
     * @Date 2018/7/2 15:09
     */
    @Configuration
    @ComponentScan("com.zhen.highlights_spring4.ch3.taskscheduler")
    @EnableScheduling
    public class TaskSchedualerConfig {
    }
    package com.zhen.highlights_spring4.ch3.taskscheduler;
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    /**
     * @author zhen
     * @Date 2018/7/2 15:10
     */
    public class Main {
        public static void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedualerConfig.class);
        }
    }
    View Code

    4、条件注解

    package com.zhen.highlights_spring4.ch3.conditional;
    
    /**
     * @author zhen
     * @Date 2018/7/2 15:32
     */
    public interface ListService {
        public String showListCmd();
    }
    package com.zhen.highlights_spring4.ch3.conditional;
    
    /**
     * @author zhen
     * @Date 2018/7/2 15:32
     */
    public class WindowsListService implements ListService {
        @Override
        public String showListCmd() {
            return "dir";
        }
    }
    package com.zhen.highlights_spring4.ch3.conditional;
    
    /**
     * @author zhen
     * @Date 2018/7/2 15:33
     */
    public class LinuxListService implements ListService {
        @Override
        public String showListCmd() {
            return "ls";
        }
    }
    package com.zhen.highlights_spring4.ch3.conditional;
    
    
    import org.springframework.context.annotation.Condition;
    import org.springframework.context.annotation.ConditionContext;
    import org.springframework.core.type.AnnotatedTypeMetadata;
    
    /**
     * @author zhen
     * @Date 2018/7/2 15:21
     */
    public class WindowsCondition implements Condition {
        @Override
        public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
            return conditionContext.getEnvironment().getProperty("os.name").contains("Windows");
        }
    }
    package com.zhen.highlights_spring4.ch3.conditional;
    
    import org.springframework.context.annotation.Condition;
    import org.springframework.context.annotation.ConditionContext;
    import org.springframework.core.type.AnnotatedTypeMetadata;
    
    /**
     * @author zhen
     * @Date 2018/7/2 15:21
     */
    public class LinuxCondition implements Condition {
        @Override
        public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
            return conditionContext.getEnvironment().getProperty("os.name").contains("Linux");
        }
    }
    package com.zhen.highlights_spring4.ch3.conditional;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Conditional;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @author zhen
     * @Date 2018/7/2 15:33
     */
    @Configuration
    public class ConditionConfig {
    
        @Bean
        @Conditional(WindowsCondition.class)
        public ListService windowsListService(){
            return new WindowsListService();
        }
    
        @Bean
        @Conditional(LinuxCondition.class)
        public ListService linuxListService(){
            return new LinuxListService();
        }
    }
    package com.zhen.highlights_spring4.ch3.conditional;
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    /**
     * @author zhen
     * @Date 2018/7/2 15:40
     */
    public class Main {
        public static void main(String[] args){
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);
            ListService listService = context.getBean(ListService.class);
            System.out.println(context.getEnvironment().getProperty("os.name") + "系统下的列表命令为: " + listService.showListCmd());
    
            context.close();
        }
    }
    View Code

    5、组合注解

    package com.zhen.highlights_spring4.ch3.annotation;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    import java.lang.annotation.*;
    
    /**
     * @author zhen
     * @Date 2018/7/2 15:48
     */
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Configuration
    @ComponentScan
    public @interface WiselyConfiguration {
        String[] value() default {};
    }
    package com.zhen.highlights_spring4.ch3.annotation;
    
    /**
     * @author zhen
     * @Date 2018/7/2 16:00
     */
    @WiselyConfiguration("com.zhen.highlights_spring4.ch3.annotation")
    public class DemoConfig {
    }
    package com.zhen.highlights_spring4.ch3.annotation;
    
    import org.springframework.stereotype.Service;
    
    /**
     * @author zhen
     * @Date 2018/7/2 15:53
     */
    @Service
    public class DemoService {
    
        public void outputResult(){
            System.out.println("从组合注解配置照样获得的bean");
        }
    }
    
    package com.zhen.highlights_spring4.ch3.annotation;
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    /**
     * @author zhen
     * @Date 2018/7/2 16:01
     */
    public class Main {
        public static void main(String[] args){
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);
            DemoService demoService = context.getBean(DemoService.class);
    
            demoService.outputResult();
    
            context.close();
        }
    }
    View Code

    6、测试

    package com.zhen.highlights_spring4.ch3.fortest;
    
    /**
     * @author zhen
     * @Date 2018/7/2 16:04
     */
    public class TestBean {
        private String content;
    
        public TestBean(String content){
            super();
            this.content = content;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    }
    package com.zhen.highlights_spring4.ch3.fortest;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Profile;
    
    /**
     * @author zhen
     * @Date 2018/7/2 16:05
     */
    @Configuration
    public class TestConfig {
    
        @Bean
        @Profile("dev")
        public TestBean devTestBean(){
            return new TestBean("from development profile");
        }
    
        @Bean
        @Profile("prod")
        public TestBean prodTestBean(){
            return new TestBean("from production profile");
        }
    }
    package com.zhen.highlights_spring4.ch3.fortest;
    
    import org.junit.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ActiveProfiles;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    /**
     * @author zhen
     * @Date 2018/7/2 16:30
     */
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = {TestConfig.class})
    @ActiveProfiles("prod")
    public class DemoBeanIntegrationTests {
    
        @Autowired
        private TestBean testBean;
    
        @Test
        public void prodBeanShouldInject(){
            String expected = "from production profile";
            String actual = testBean.getContent();
            Assert.assertEquals(expected, actual);
        }
    }
    View Code
  • 相关阅读:
    「学习记录」《数值分析》第三章计算实习题(Python语言)
    Set原理
    字符串流stringReader
    Collection List接口
    io
    Dubbo 服务容错Hystrix
    Duboo 与springboot整合
    读取配置文件
    springboot 端口号
    springboot 多环境选择
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/9254910.html
Copyright © 2020-2023  润新知