个人学习Spring 手动装配之条件装配(二.接口编程实现)笔记

    xiaoxiao2025-07-06  6

    个人学习Spring 手动装配之条件装配(二.接口编程实现)笔记

    话不多说,@Conditiional和实现Condition接口就可以了

    show my code

    package com.example.demo.bootstrap; import com.example.demo.annotation.ConditionalOnSystemProperty; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.WebApplicationType; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; @Slf4j public class ConditionOnSystemPropertyBootstrap { @Bean @ConditionalOnSystemProperty(name = "user.name",value = "yihan") public String helloWorld(){ return "hello world 2019"; } public static void main(String[] args) { ConfigurableApplicationContext context = new SpringApplicationBuilder(ConditionOnSystemPropertyBootstrap.class) .web(WebApplicationType.NONE) .run(args); String helloWorld = context.getBean("helloWorld", String.class); log.info("condition Success: result={}",helloWorld); context.close(); } } package com.example.demo.annotation; import com.example.demo.condition.ConditionOnSystemProperty; import org.springframework.context.annotation.Conditional; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.CONSTRUCTOR,ElementType.TYPE,ElementType.METHOD}) @Conditional(ConditionOnSystemProperty.class) public @interface ConditionalOnSystemProperty { String name(); String value(); } package com.example.demo.condition; import com.example.demo.annotation.ConditionalOnSystemProperty; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; import java.util.Map; @Slf4j public class ConditionOnSystemProperty implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(ConditionalOnSystemProperty.class.getName()); String name = String.valueOf(annotationAttributes.get("name")); String value = String.valueOf(annotationAttributes.get("value")); String username = System.getProperty(name); log.info("name=[{}],value=[{}]",name,value); return value.equals(username); } }

    参考书籍:Sprinboot 编程思想

    最新回复(0)