个人学习Spring 手动装配之条件装配(一.注解实现)笔记

    xiaoxiao2025-05-21  44

    个人学习Spring 手动装配之条件装配(一.注解实现)笔记

    在向容器装配对象的时候,有的情况我们需要根据不同的条件装配不同的对象,我们称这种装配方式为条件装配,条件装配有两种实现,一种是基于注解的实现,另一种是基于编程的实现,这篇文章将讲述如何根据注解来实现条件装配

    show my code

    package com.example.demo.service; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; /** * sum 求和for 循环实现 */ @Profile("Java7") @Service @Slf4j public class Java7CalculateService implements CalculateService{ @Override public Integer sum(Integer... args) { log.info("Java 7 实现"); Integer result =0; for (int i = 0; i < args.length; i++) { result+=args[i]; } return result; } } package com.example.demo.service; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; import java.util.stream.Stream; /** * sum 求和lambda实现 */ @Profile("Java8") @Service @Slf4j public class Java8CalculateService implements CalculateService{ @Override public Integer sum(Integer... args) { log.info("Java 8 实现"); return Stream.of(args).reduce(0,Integer::sum); } } package com.example.demo.service; public interface CalculateService { /** * sum 求和 * @param args 待求和参数 * @return 求和结果 */ public Integer sum(Integer... args); } package com.example.demo.bootstrap; import com.example.demo.service.CalculateService; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = "com.example.demo.service") public class CalculateServiceBootstrap { public static void main(String[] args) { ConfigurableApplicationContext context = new SpringApplicationBuilder(CalculateServiceBootstrap.class) .web(WebApplicationType.NONE) .profiles("Java7") .run(args); CalculateService calculateService = context.getBean(CalculateService.class); System.out.println(calculateService.sum(0,1,2,3,4,5,6,7,8,9,10)); context.close(); } }

    参考书籍: springboot 编程思想

    最新回复(0)