Bootstrap

SpringBoot整合策略模式之基于 ApplicationContextAware + 枚举类实现

1、ILog

package com.atguigu.design.demo.spring;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public interface ILog {

    void log(String msg);

    LogType getType();
}
@Component
class FileLog implements ILog {
    @Override
    public void log(String msg) {
        System.out.println("输出日志到文件:"  + msg);
    }

    @Override
    public LogType getType() {
        return LogType.FILE_LOG;
    }
}
@Component
class ConsoleLog implements ILog {
    @Override
    public void log(String msg) {
        System.out.println("输出日志到控制台:" + msg);
    }

    @Override
    public LogType getType() {
        return LogType.CONSOLE_LOG;
    }
}
@Component
class LogClient implements ApplicationContextAware {

    private static final Map<String, ILog> MAP = new ConcurrentHashMap<>();

    /*
    @Autowired
    private FileLog fileLog;

    @Autowired
    private ConsoleLog consoleLog;

    @PostConstruct
    public void init() {
        MAP.put("1", fileLog);
        MAP.put("2", consoleLog);
    }
    */

    /**
     * 根据类型记录日志信息
     *
     * @param type 日志类型,用于区分不同类型的日志
     * @param msg 待记录的消息
     */
    public void log(String type, String msg) {
        MAP.get(type).log(msg);
    }

    /**
     * 设置应用上下文,用于初始化日志策略
     * 该方法通过应用上下文获取所有类型的日志策略,并将其初始化
     *
     * @param applicationContext 应用上下文
     * @throws BeansException 如果无法从应用上下文中获取日志策略,抛出该异常
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取所有实现ILog接口的Bean
        Map<String, ILog> beansOfType = applicationContext.getBeansOfType(ILog.class);
        // 如果没有找到任何ILog实现,则直接返回
        if (CollectionUtils.isEmpty(beansOfType)) {
            return;
        }
        // 将Map中的值转换为Collection类型
        Collection<ILog> beans = beansOfType.values();

        // 遍历所有日志策略Bean,将它们按照类型添加到MAP中
        beans.forEach(bean->{
            // 获取日志策略的类型
            LogType type = bean.getType();
            // 将日志策略添加到MAP中,以便后续根据类型获取对应的日志策略
            MAP.put(type.type, bean);
        });
    }
}

2、LogType 枚举类

package com.atguigu.design.demo.spring;
public enum LogType {
    FILE_LOG("1","文件日志"),
    CONSOLE_LOG("2","控制台日志")
    ;

    public String type;
    public String desc;

    LogType(String type, String desc) {
        this.type = type;
        this.desc = desc;
    }
}

3、DemoController

package com.atguigu.design.demo.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
    @Autowired
    private LogClient logClient;

    @GetMapping("log/{type}")
    public String log(@PathVariable String type, @RequestParam("msg") String msg) {
        logClient.log(type, msg);
        return "日志输出成功!";
    }
}


4、application.properties

spring.application.name=design-demo
server.port=10010


5、DesignDemoApplication

package com.atguigu.design.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


// Generated by https://start.springboot.io
// 优质的 spring/boot/data/security/cloud 框架中文文档尽在 => https://springdoc.cn
@SpringBootApplication
public class DesignDemoApplication {

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

}


在这里插入图片描述

;