springboot多例模式的实现

在bean类中加注解@Scope(“prototype”) 发现仍然是单例模式。
代码如下:
service

/**
 * @author Kern
 * @Title: ExcelTemplateServiceImpl
 * @ProjectName swms-java
 * @Description: TODO
 * @date 2019-7-815:14
 */
@Scope("prototype")
@Service
public class ExcelTemplateServiceImpl implements IExcelTemplateService {

    private static Logger logger = LoggerFactory.getLogger(ExcelTemplateServiceImpl.class);
    @Autowired
    private ISysDocParamConfService docParamConfService;
    @Autowired
    private ISysDocConfService docConfService;

    //根据POI封装的一些工具类
    private POIStyleTools styleTools;
    private POIDataTools dataTools;
    private POIAutoTools autoTools;
    //头部注释行样式和字体
    private CellStyle topicContextStyle;
    private Font topicContextFont;
    //表头样式和字体
    private CellStyle headContextStyle;
    private Font headContextFont;
    //正文样式和字体
    private CellStyle contextStyle;
    private Font contextFont;
    //默认的workbook,用于生成样式和字体
    private Workbook defWorkbook;

    private final static String DEF_DICT_ARR_SHEET_NAME = "hidden";
    /**
     * 初始化方法 谨慎修改
     */
    @PostConstruct
    public void init() {
        defWorkbook = new HSSFWorkbook();
        styleTools = POIBox.openStyleTool();
        dataTools = POIBox.openDataTool();
        autoTools = POIBox.openAutoTool();

        topicContextStyle = styleTools.getDefCellStyle(defWorkbook, false, true);
        topicContextFont = styleTools.getFont(defWorkbook, "宋体", (short)11);
        topicContextStyle.setFont(topicContextFont);

        headContextStyle = styleTools.getDefCellStyle(defWorkbook, true, true);
        styleTools.setBackGroundColor(headContextStyle, HSSFColor.BLUE_GREY.index);
        headContextFont = styleTools.getFont(defWorkbook, "宋体", (short)13);
        headContextFont.setColor(HSSFColor.WHITE.index);
        headContextStyle.setFont(headContextFont);

        contextStyle = styleTools.getDefCellStyle(defWorkbook, false, true);
        contextFont = styleTools.getFont(defWorkbook, "宋体",  (short)11);
        contextStyle.setFont(contextFont);
    }

    @Override
    public void download(Integer templateType, HttpServletResponse response) throws BizException {
        //TODO 下载文档模板
    }
}

contorller

@RequestMapping("/file")
@RestController
@Api(value = "/file", basePath = "file", description = "文档文件管理", produces = MediaType.APPLICATION_JSON_VALUE)
public class FileManageController {

    @Autowired
    private IExcelTemplateService excelTemplateService ;

    @GetMapping("/template/{templateType}")
    @ApiOperation(value = "/template/{templateType}",notes = "模板下载")
    public Response templateDownload(
            @PathVariable("templateType") Integer templateType,
            HttpServletResponse response) throws BizException {
        this.excelTemplateService.download(templateType, response);
        return ResponseUtil.returnSuccess(ResponseCodeEnum.SUCCESS.getMsg());
    }

}

不知道因为什么原因,@scope注解的类无法实现由@autowird注入的bean的单例和多例的配置,将代码修改为由bean工厂的getBean方法获取bean,则可以实现多例模式 。service不变,controller 修改如下
controller

@RequestMapping("/file")
@RestController
@Api(value = "/file", basePath = "file", description = "文档文件管理", produces = MediaType.APPLICATION_JSON_VALUE)
public class FileManageController {

    @Autowired
    private BeanFactory beanFactory;

    @GetMapping("/template/{templateType}")
    @ApiOperation(value = "/template/{templateType}",notes = "模板下载")
    public Response templateDownload(
            @PathVariable("templateType") Integer templateType,
            HttpServletResponse response) throws BizException {
        IExcelTemplateService excelTemplateService = beanFactory.getBean(IExcelTemplateService.class);
        excelTemplateService.download(templateType, response);
        return ResponseUtil.returnSuccess(ResponseCodeEnum.SUCCESS.getMsg());
    }

}

后记

@Autowired 在项目启动时已经将bean实例注入到引用类的成员变量中,因此在调用时是直接引用了已被初始化的成员变量,不会再从bean工厂中获取,因此没办法实现多例。也就是说多例模式,必须从bean工厂获取bean才能够实现。

  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
好的,下面我给你讲一下如何在Spring Boot中实现策略模式。 首先,我们需要定义一个接口或者抽象类,用于定义策略模式中的抽象行为。以一个简单的计算器为例,我们可以定义一个`Calculator`接口,其中包含一个`calculate`方法: ```java public interface Calculator { int calculate(int a, int b); } ``` 然后,我们需要定义具体的策略类,实现`Calculator`接口。假设我们有两种计算方式:加法和乘法,我们可以分别定义两个实现类: ```java @Component public class AddCalculator implements Calculator { @Override public int calculate(int a, int b) { return a + b; } } @Component public class MultiplyCalculator implements Calculator { @Override public int calculate(int a, int b) { return a * b; } } ``` 在上面的代码中,我们使用了`@Component`注解将这两个类注册为Spring Bean,以便在其他地方可以自动注入它们。 接下来,我们需要一个Context类,用于选择具体的策略类。在Spring Boot中,我们可以使用`@Autowired`注解自动注入所有实现了`Calculator`接口的Bean,并使用`@Qualifier`注解来指定具体的实现类。例如: ```java @Service public class CalculatorService { @Autowired private List<Calculator> calculators; public int calculate(String operator, int a, int b) { for (Calculator calculator : calculators) { if (calculator.getClass().getSimpleName().equalsIgnoreCase(operator)) { return calculator.calculate(a, b); } } throw new IllegalArgumentException("Invalid operator: " + operator); } } ``` 在上面的代码中,我们使用了一个`List<Calculator>`来注入所有实现了`Calculator`接口的Bean。然后,我们在`calculate`方法中根据传入的运算符选择具体的策略类,并调用它的`calculate`方法进行计算。 最后,我们可以在Controller中使用`CalculatorService`类来实现具体的业务逻辑。例如: ```java @RestController public class CalculatorController { @Autowired private CalculatorService calculatorService; @GetMapping("/calculate") public int calculate(@RequestParam String operator, @RequestParam int a, @RequestParam int b) { return calculatorService.calculate(operator, a, b); } } ``` 在上面的代码中,我们使用了`@RequestParam`注解来接收请求参数,然后调用`CalculatorService`的`calculate`方法进行计算,并返回结果。 这就是在Spring Boot中实现策略模式的方法。希望对你有帮助!
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值