(4)springboot-ApplicationContextAware + @Async 异步注解 + @Scheduled + 组合注解

目录

ApplicationContextAware

@Async注解

@Scheduled

组合注解


ApplicationContextAware

ApplicationContextAware 通过它Spring容器会自动把上下文环境来回去bean或者set bean。

本案例结合多数据源来实现。

step 1 :

@Component
@Lazy(false)
public class SpringContextAware implements ApplicationContextAware {
    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    /**
     *
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }


    /**
     * 获取配置文件配置项的值
     *
     * @param key 配置项key
     */
    public static String getEnvironmentProperty(String key) {
        return getApplicationContext().getEnvironment().getProperty(key);
    }

    /**
     * 获取spring.profiles.active
     */
    public static String getActiveProfile() {
        return getApplicationContext().getEnvironment().getActiveProfiles()[0];
    }
}

step 2:

配置多数据源

spring.datasource.db1.type=org.apache.commons.dbcp2.BasicDataSource
spring.datasource.db1.driverClassName=ru.yandex.clickhouse.ClickHouseDriver
spring.datasource.db1.url=jdbc:clickhouse://192.168.5.110:12345/data_test
spring.datasource.db1.username=default
spring.datasource.db1.password=Bmsoft2019datateam
#最大建立连接等待时间。如果超过此时间将接到异常,单位毫秒
spring.datasource.db1.maxWait=8000
spring.datasource.db1.initialSize=10
spring.datasource.db1.minIdle=50
spring.datasource.db1.maxIdle=250
spring.datasource.db1.maxActive=300
spring.datasource.db1.removeAbandoned=true
#从getconn到sql执行完,超过10秒会被释放
spring.datasource.db1.removeAbandonedTimeout=10

spring.datasource.db2.type=org.apache.commons.dbcp2.BasicDataSource
spring.datasource.db2.driverClassName=ru.yandex.clickhouse.ClickHouseDriver
spring.datasource.db2.url=jdbc:clickhouse://192.168.5.112:12345/data_test
spring.datasource.db2.username=default
spring.datasource.db2.password=Bmsoft2019datateam
spring.datasource.db2.maxWait=8000
spring.datasource.db2.initialSize=10
spring.datasource.db2.minIdle=10
spring.datasource.db2.maxIdle=250
spring.datasource.db2.maxActive=300
spring.datasource.db2.removeAbandoned=true
spring.datasource.db2.removeAbandonedTimeout=10
@Configuration
public class DbConfig {

    /**
     * Title: dataSource1 Description: TODO
     *
     * @return DataSource remark : prefix 为 application.properteis中对应属性的前缀
     */
    @Bean(name = "db1")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
        //return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }

    @Bean(name = "db2")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
        //return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }

}

step3:

 public static JdbcTemplate getDefaultTemplate() {


        Object bean = SpringContextAware.getBean("db1");
        if (null == bean) {
            return null;
        }
        DataSource dataSource = (DataSource) bean;
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        JdbcTemplate bmTemplate = jdbcTemplate;

        return bmTemplate;
    }

    public static JdbcTemplate getDefaultTemplate2() {

        Object bean = SpringContextAware.getBean("db2");
        if (null == bean) {
            return null;
        }
        DataSource dataSource = (DataSource) bean;
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        JdbcTemplate bmTemplate = jdbcTemplate;

        return bmTemplate;
    }

@Async注解

1、创建一个普通类,并注入到IOC容器中,并在该类的方法上标注@Async注解

@Component
public class CountNumber {
    @Async
    public void PrintNumber(){
        for(int i=1; i<10; i++){
            System.out.println("i = " + i);
        }
    }
}

2、从spring boot启动类中获取IOC中的bean,在启动类上标注@EnableAsync注解,启动@Async异步注解。或者在启动类中只标注@SpringBootApplication注解,因为该注解中已经包含了上面两个注解。

/*@SpringBootApplication注解与@ComponentScan、@EnableAsync注解达到相同的功效*/
//@SpringBootApplication
@ComponentScan
@EnableAsync
public class Springboot3Application {

    public static void main(String[] args) throws Exception {

        ConfigurableApplicationContext context = SpringApplication.run(Springboot3Application.class, args);

        /*@Async和@EnableAsync配合使用*/
    context.getBean(CountNumber.class).PrintNumber();
        for(int i=1; i<10; i++){
            TimeUnit.MICROSECONDS.sleep(1);
            System.out.println("------------------");
        }
        context.close();
    }
}

3、执行启动类,输出结果如下:

如果不使用异步注解,结果如下:

 


@Scheduled

一、项目启动类添加@EnableScheduling注解

@EnableScheduling
public class TaskApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(TaskApplication.class, args);
    }
 
}

二、使用@Component和@Scheduled(cron="0/5 * * * * ?")启动定时任务

package com.example.task.timing;
 
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
@Component
public class TimingTask {
    /**
     *  每五秒执行一次
     */
    @Scheduled(cron="0/5 * * * * ?")
    public void executeFileDownLoadTask() {
        System.out.println("定时任务启动");
    }
}

涉及到的参数有:cron、zone、fixedDelay、fixedDelayString、fixedRate等

参考:https://www.jianshu.com/p/1defb0f22ed1


组合注解

所谓的组合注解就是和元注解区分开,组合注解是我们自己声明创建的,组合注解包含多个元注解的功能。

首先创建一个组合注解,这个组合注解包含元注解@Configuration和@ComponentScan的功能

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan
public @interface CombineAnnotation {
     String[] value();
}

创建demo的bean


@Service
public class DemoBean {
 
    public  void output(){
        System.out.println("bean容器中注册了");
    }

编写配置文件应用组合注解

@CombineAnnotation("com.example.demo")
public class MyConfig {
}

编写main函数

@SpringBootApplication
public class DemoCombineannotationApplication {
 
	public static void main(String[] args) {
		SpringApplication.run(DemoCombineannotationApplication.class, args);
 
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
		DemoBean demo =context.getBean(DemoBean.class);
		demo.output();
		context.close();
	}
}

 

AnnotationConfigApplicationContext(String... basePackages)

构造方法自动扫描指定的包路径下的@Configration注解的类

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值