• spring 的常用功能


    1. spring 自定义配置变量,使用
    properties 文件中的写法
    # 日志检查时间,默认是半小时
    task.base.period=120
    java 代码中的写法@Value("${task.base.period}")private String basePeriod;
    2. spring 定时器使用
    2.1 使用默认的注解定时
    @Component
    public class CJ01ErrorListener {
        public static volatile boolean isStop= false;
        private RestTemplate restTemplate = new RestTemplate();
        @Scheduled(cron = "*/5 * * * * ?")
        public void errorSendToEmail() {
            SendEmail.send();
        }
    }

    2.2 使用默认的注解,不能够动态的修改定时间,想要动态的修改定时时间,可以使用ThreadPoolTaskScheduler 类

        @Autowired
        private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    开启一个定时任务写法如下:

    ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(task,
                        new CronTrigger("0/5 * * * * ?"));

    停止一个任务可以调用future.cancel(true) 方法。修改定时任务时间可以下停止任务,再新建一个定时任务。

    3 spring 启动后自动执行代码,可以利用spring的监听事件ApplicationListener 实现启动后自动执行,下面给出一个自动执行的例子。

    @Configuration
    public class ScheduleConfigInitListener implements ApplicationListener<ContextRefreshedEvent> {
        protected Logger logger= LoggerFactory.getLogger(DataController.class);
        @Autowired
        private MonitorTaskManager taskmanager;
        @Override
        public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
            // 执行自己的代码
            taskmanager.startAllTask();
        }
    }

    4. spring 通过bean的名字获取bean , 实现ApplicationContextAware 接口后就可以得到spring applicationContext,从而得到bean,下面给出一个实现类

    @Component
    public class SpringContextUtil implements ApplicationContextAware {
        private static ApplicationContext context = null;
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.context = applicationContext;
        }
        public static ApplicationContext getContext(){
            return context;
        }
        public static <T> T getBean(String beanName){
            return (T) context.getBean(beanName);
        }
        public static String getMessage(String key){
            return context.getMessage(key, null, Locale.getDefault());
        }
    }

    在代码中调用

    // 获取环境变量
    SpringContextUtil.getContext().getEnvironment()
                    .getProperty("sanss.elasticsearch.port",Integer.class);
    // 获取bean
    SpringContextUtil.getBean("alertLogRepository");

    5. spring 中连接数据库及使用jpa

    5.1 连接数据库

    spring.datasource.url=jdbc:mysql://localhost:3306/alert?serverTimezone=GMT%2B8
    spring.datasource.username=root
    spring.datasource.password=root

    5.2 使用jpa

    在properties 中配置jpa ,从java代码创建数据库表

    # 设置为none则不创建表,具体的可以查spring的配置
    spring.jpa.hibernate.ddl-auto=none

    在代码中使用jpa , 继承 JpaRepository<Sms, Long> 该接口就可以了,而JpaRepository又继承CrudRepository,因此,CrudRepository 又提供了好多基础的方法

    在代码中继承JpaRepository 接口

    public interface SmsRepository extends JpaRepository<Sms, Long> {
      List<MonitorConfig> findByBelong(Short belong);
    }

    6. spring 中使用连接 kafka

    properties 文件中配置

    spring.kafka.bootstrap-servers=172.31.4.124:9092,172.31.4.125:9092

    代码中使用

    @Component
    public class Sender {
        @Autowired
        private KafkaTemplate<String, String> kafkaTemplate;
        public void sendMessage(String topic, String data) {
            kafkaTemplate.send(topic, data);
        }
    }
  • 相关阅读:
    IPFS实践之初体验
    自己写的屏幕录像及播放软件
    绿色ip扫描工具
    ASIHTTPRequest 编码问题
    ios开发中,A valid provisioning profile for this executable was not found,的解决方法
    毕业设计之蚁群算法的研究——起始篇
    分享两个模拟get和post方法的工具类,让应用能够与服务器进行数据交互
    安卓中生成二维码和扫描二维码
    分享一个安卓中异步获取网络图片并自适应大小的第三方程序(来自github)
    不只是个程序员
  • 原文地址:https://www.cnblogs.com/gongpipi/p/8178640.html
Copyright © 2020-2023  润新知