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);
    }
}
原文地址:https://www.cnblogs.com/gongpipi/p/8178640.html