1.Spring Aware
1. 点睛
1.1 Spring依赖注入最大的亮点是你所有的Bean对Spring容器的存在是没有意识的。即你可以将你的容器替换成别的容器,这时Bean之间的耦合度很低。
1.2 但是实际项目中,不可避免用到Spring容器本身的功能资源,这时你的Bean必须要意识到Spring容器的存在,才能调用Spring所提供的资源,即所谓的Spring Aware;
1.3 其实Spring Aware本身就是Spring设计用来框架内部使用的,使Bean和Spring框架耦合。
1.4 Spring Aware目的是为了让Bean获得Spring容器服务。因为ApplicationContext接口集成了MessageSource接口,ApplicationEventPublisher接口和ResourceLoader接口,所以Bean继承ApplicationContextAware可以获得Spring容器所有的服务,但原则上用到啥接口就实现啥接口。
2. 示例
2.1 新建test.txt供外部资源加载使用
2.2 演示类:
代码解释:
实现BeanNameAware, ResourceLoaderAware,获得Bean名称和资源加载的服务;
BeanNameAware—>重写setBeanName();
ResourceLoaderAware—>重写setResourceLoader()
package com.leonard2;
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 sun.misc.IOUtils;
import sun.nio.ch.IOUtil;
import java.io.IOException;
@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware {
private String beanName;
private ResourceLoader loader;
@Override
public void setBeanName(String s) {
this.beanName = s;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.loader = resourceLoader;
}
public void outputResult(){
System.out.println("bean的名称"+beanName);
Resource resource = loader.getResource("com/leonard2/test.txt");
try {
System.out.println("Loader加载的文件内容为:"+resource.getInputStream());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
2.3 配置类
@Configuration
@ComponentScan("com.leonard2")
public class AwareConfig {
}
2.4 运行类
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
AwareService bean = context.getBean(AwareService.class);
bean.outputResult();
context.close();
}
}
2.多线程
1.点睛
Spring通过任务执行器(TaskExwcutor)实现多线程和并发编程;
使用ThreadPoolTaskExecutor实现一个基于线程池的TaskExecutor;
实际开发一般都是异步的,所有需要在配置类中通过@EnableAsync开启异步任务支持,并且需要在实际执行的Bean方法使用@Async注解声明其是一个异步任务
2.示例
2.1 配置类 TaskExecutorConfig
@EnableAsync//注解开启异步任务支持
配置类实现AsyncConfigurer 重写getAsyncExecutor();
返回ThreadPoolTaskExecutor,获得基于线程池的TaskExecutor;
package com.leonard3;
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 Leonard.Z
* @date 2020/9/24 17:36
* @des 配置类实现AsyncConfigurer 重写getAsyncExecutor();
* 返回ThreadPoolTaskExecutor,获得基于线程池的TaskExecutor
*/
@Configuration
@ComponentScan("com.leonard3")
@EnableAsync//注解开启异步任务支持
public class TaskExecutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
2.2 任务执行类 AsyncTaskService
通过@Async注解声明该方法是异步方法;
如果注解在类级别,则代表该类所有方法都是异步方法;
这里的方法自动被注入使用【ThreadPoolTaskExecutor】作为【TaskExecutor】
package com.leonard3;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* @author Leonard.Z
* @date 2020/9/24 17:46
* @des 任务执行类
*/
@Service
public class AsyncTaskService {
@Async
public void executeAsyncTask(Integer i){
System.out.println("执行异步任务:"+i);
}
@Async
public void executeAsyncTask2(Integer i){
System.out.println("执行异步任务+1:"+(i+1));
}
}
2.3 运行
执行结果是并发执行而不是顺序执行
执行异步任务:0
执行异步任务:1
执行异步任务:2
执行异步任务+1:2
执行异步任务:4
执行异步任务+1:5
执行异步任务+1:1
执行异步任务:5
执行异步任务:6
执行异步任务+1:4
执行异步任务:3
执行异步任务+1:3
执行异步任务+1:8
执行异步任务:7
执行异步任务+1:7
执行异步任务+1:6
执行异步任务+1:10
执行异步任务:9
执行异步任务+1:9
执行异步任务:8
package com.leonard3;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author Leonard.Z
* @date 2020/9/24 17:49
* @des Main
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
AsyncTaskService ser = context.getBean(AsyncTaskService.class);
for (int i = 0; i < 10; i++) {
ser.executeAsyncTask(i);
ser.executeAsyncTask2(i);
}
context.close();
}
}
3.计划任务
1.点睛
- 在配置类注解@EnableScheduling开启对计划任务的支持;
- 在要执行计划任务的方法上注解@Scheduled,声明这是一个计划任务。
【@Scheduled】支持多种类型计划任务,包括【cron】,【fixDelay】,【fixRate】
2.示例
2.1 计划任务执行类 ScheduleTaskServcie
【@Scheduled】 声明该方法是个计划任务,使用【fixedRate】属性每隔固定时间执行
【cron】属性按照固定时间执行,本例指每天11点28分执行
package com.leonard4;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author Leonard.Z
* @date 2020/9/26 10:17
* @des 计划任务执行类
* @Scheduled 声明该方法是个计划任务,使用fixedRate属性每隔固定时间执行
* cron属性按照固定时间执行,本例指每天11点28分执行
*/
@Service
public class ScheduleTaskServcie {
private static final SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void rptCurrentTime(){
System.out.println("每隔五秒执行一次:"+fmt.format(new Date()));
}
@Scheduled(cron = "0 14 16 ? * *")
public void fixTimeExecution(){
System.out.println("在指定时间"+fmt.format(new Date())+"执行");
}
}
2.2 配置类 :ScheduleTaskConfig
通过【@EnableScheduling】 开启对计划任务的支持
package com.leonard4;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author Leonard.Z
* @date 2020/9/26 10:46
* @des 配置类
* @EnableScheduling 开启对计划任务的支持
*/
@Configuration
@ComponentScan("com.leonard4")
@EnableScheduling
public class ScheduleTaskConfig {
}
2.3 运行 Main
每隔5秒输出一次,@Scheduled(cron = “0 14 16 ? * *”)指定时间点会输出一次
package com.leonard4;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author Leonard.Z
* @date 2020/9/26 16:08
* @des 每隔五秒执行一次:16:13:58
* 在指定时间16:14:00执行
* 每隔五秒执行一次:16:14:03
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScheduleTaskConfig.class);
}
}
4.条件注解@Conditional
1.点睛
@Conditional根据满足某一特定条件创建一个特定Bean,即根据特定条件来控制Bean的创建行为,利用这一特性进行一些自动配置。
【以不同操作系统为例】:
通过实现【Condition】接口,重写【matches】方法构造判读条件,若在Windows系统运行,输出‘dir’;若再Linux系统运行,输出‘ls’。
2.示例
1.判断条件定义
package com.leonard5;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* @author Leonard.Z
* @date 2020/9/28 10:31
* @des 判断条件定义-Windows
*/
public class WindowsCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Windows");
}
}
package com.leonard5;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* @author Leonard.Z
* @date 2020/9/28 10:35
* @des Linux 系统 判断
*/
public class LinuxWindows implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getEnvironment().getProperty("os.name").contains("Linux");
}
}
2.不同系统下Bean类,实现一个公共接口
接口
package com.leonard5.i;
/**
* @author Leonard.Z
* @date 2020/9/28 10:37
* @des 接口
*/
public interface ListService {
public String showListcmd();
}
Windows下创建的Bean类
package com.leonard5.bean;
import com.leonard5.i.ListService;
/**
* @author Leonard.Z
* @date 2020/9/28 10:39
* @des WindowsListService 下创建的Bean类
*/
public class WindowsListService implements ListService {
@Override
public String showListcmd() {
return "dir";
}
}
Linux下创建的Bean类
package com.leonard5.bean;
import com.leonard5.i.ListService;
/**
* @author Leonard.Z
* @date 2020/9/28 10:45
* @des
*/
public class LinuxListService implements ListService {
@Override
public String showListcmd() {
return "ls";
}
}
3.配置类
通过@Conditional注解:
符合Windows条件则实例化windowsListService
符合Linux条件则实例化LinuxListService
package com.leonard5.config;
import com.leonard5.LinuxWindows;
import com.leonard5.WindowsCondition;
import com.leonard5.bean.LinuxListService;
import com.leonard5.bean.WindowsListService;
import com.leonard5.i.ListService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConditionConfig {
@Bean
@Conditional(WindowsCondition.class)
public ListService windowsListSerice(){
return new WindowsListService();
}
@Bean
@Conditional(LinuxWindows.class)
public ListService linuxListService(){
return new LinuxListService();
}
}
4.运行【Windows系统下运行】
输出结果:
Windows 10系统下的命令为:dir
package com.leonard5;
import com.leonard5.config.ConditionConfig;
import com.leonard5.i.ListService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author Leonard.Z
* @date 2020/9/28 10:48
* @des
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);
ListService bean = context.getBean(ListService.class);
System.out.println(context.getEnvironment().getProperty("os.name")+"系统下的命令为:"+bean.showListcmd());
context.close();
}
}
5.组合注解与元注解
1.【元注解】:实质上就是注解到别的注解上的注解,被注解的注解就是【组合注解】,组合注解具备元注解的功能;
2.【例如】@Configuration和@ComponentScan就是一个【组合注解】,表明这个类也是一个Bean;
3.使用【@WiselyConfiguration】注解替换@Configuration和@ComponentScan就是一个【组合注解】